6.1. Functions¶
In Python, a function is a named sequence of statements that belong together. Their primary purpose is to help us organize programs into chunks that match how we think about the solution to the problem.
import turtle
def main() -> None:
for i in range(0, 4, 1):
turtle.forward(50.0)
turtle.left(90.0)
return None
main()
(ch04_1)
The above function, called main, draws a sqaure. The function has two parts. The first part, the function definition, is lines 6 through 7, and specifies what the function does when it is executed. The second part, the function call is line 9 and it executes the functions.
There can be any number of statements inside the function definition,
but they have to be indented from the def
. In the examples in this
book, we will use the standard indentation of four spaces. Function
definitions are the second of several compound statements we will
see, all of which have the same pattern:
A header line which begins with a keyword and ends with a colon.
A body consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header line.
We’ve already seen the for
loop which follows this pattern.
In a function definition, the keyword in the header is def
, which
is followed by the name of the function and the return type. We will
go into the purpose of the return type in a later chapter.
Defining a new function does not make the function run. To do that we
need a function call. This is also known as a function
invocation. We’ve already seen how to call some built-in functions
like print
, range
and int
. So in the second to the last
line of the program, we call the function to actually raw the square.
It is worth noting that a program with functions does not neccessarily execute its lines of code from top to bottom. Because the function code is only executed when it is called, the program execution can jump around. To see this in action, step through the animation of the following program:
Python 3.3
Step 1 of 9 line that has just executed next line to execute Visualized using Online Python Tutor by Philip Guo |
| |||||||||||||||||||
(ch04_1_2)
Check your understanding
func-1-1: What is a function in Python?
func-1-2: What is one main purpose of a function?