Section 8.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.
The syntax for a function definition is:
def name( parameters ):
statements
You can make up any names you want for the functions you create, except that you can’t use a name that is a Python keyword, and the names must follow the rules for legal identifiers that were given previously. The parameters specify what information, if any, you have to provide in order to use the new function. Another way to say this is that the parameters specify what the function needs to do its work.
There can be any number of statements inside the function, 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 while
and for
loops which follow this pattern.
In a function definition, the keyword in the header is def
, which is followed by the name of the function and some parameters enclosed in parentheses. The parameter list may be empty, or it may contain any number of parameters separated from one another by commas. In either case, the parentheses are required.
We need to say a bit more about the parameters. In the definition, the parameter list is more specifically known as the formal parameters. This list of names describes those things that the function will need to receive from the user of the function. When you use a function, you provide values to the formal parameters.
The figure below shows this relationship. A function needs certain information to do its work. These values, often called arguments or actual parameters, are passed to the function by the user.
This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the “black-box”.
Suppose we’re working with lists of numeric data and a common operation we need is to find the size of the range of numbers in a list. It would make sense if we did not have to duplicate all the steps each time we want to find the size of the range. "printRange" can be thought of as an abstraction of a number of smaller steps. We will need to provide one piece of information for the function to do its work: the list we need the range of.
Here is a program containing a function to capture this idea. Give it a try.
This function is named printRange
. It has one parameter --- a variable storing a list of numbers. In the function definition this parameter is called lst
. Make sure you know where the body of the function ends — it depends on the indentation and the blank lines don’t count for this purpose!
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
. Function calls contain the name of the function to be executed followed by a list of values in parentheses, called arguments, which are assigned to the parameters in the function definition. So in the last line of the program, we call the function, and pass my_list1
as the list to be analyzed.
Once we’ve defined a function, we can call it as often as we like and its statements will be executed each time we call it. In this case, we could use it to get the size of the range of multiple lists. Make sure you can identify all three invocations of the printRange
function.
Check your understanding
Checkpoint 8.1.4.
What is a function in Python?
A named sequence of statements.
- Yes, a function is a named sequence of statements.
Any sequence of statements.
- While functions contain sequences of statements, not all sequences of statements are considered functions.
A mathematical expression that calculates a value.
- While some functions do calculate values, the python idea of a function is slightly different from the mathematical idea of a function in that not all functions calculate values. Consider, for example, the turtle functions in this section. They made the turtle draw a specific shape, rather than calculating a value.
A statement of the form x = 5 + 4.
- This statement is called an assignment statement. It assigns the value on the right (9), to the name on the left (x).
Checkpoint 8.1.5.
What is one main purpose of a function?
To improve the speed of execution
- Functions have little effect on how fast the program runs.
To help the programmer organize programs into chunks that match how they think about the solution to the problem.
- While functions are not required, they help the programmer better think about the solution by organizing pieces of the solution into logical chunks that can be reused.
All Python programs must be written using functions
- In the first several chapters, you have seen many examples of Python programs written without the use of functions. While writing and using functions is desirable and essential for good programming style as your programs get longer, it is not required.
To calculate values.
- Not all functions calculate values.
Checkpoint 8.1.6.
Checkpoint 8.1.7.
What is the name of the following function?
def printSquare(size):
"""Print a square of asterices with side size."""
for i in range(size):
print("*"*size)
def printSquare(size)
- This line is the complete function header (except for the semi-colon) which includes the name as well as several other components.
printSquare
- Yes, the name of the function is given after the keyword def and before the list of parameters.
printSquare(size)
- This includes the function name and its parameters
Print a square of asterices with side size.
- This is a comment stating what the function does.
Checkpoint 8.1.8.
What are the parameters of the following function?
def printSquare(size):
"""Print a square of asterices with side size."""
for i in range(size):
print("*"*size)
i
- i is a variable used inside of the function, but not a parameter, which is passed in to the function.
size, i
- i is a variable used inside of the function, but not a parameter, which is passed in to the function.
size
- Yes, the function specifies one parameter: size.
"*"*size
- This is an argument provided to the call to print().
Checkpoint 8.1.9.
Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a variable named my_size.
def printSquare(size):
"""Print a square of asterices with side size."""
for i in range(size):
print("*"*size)
def printSquare(size)
- No, size is the name of the formal parameter to this function. When the function is called, it requires an actual value to be passed in.
printSquare
- A function call always requires parentheses after the name of the function.
printSquare(10)
- Yes, this would work
printSquare(my_size)
- Yes, this would work since my_size is already defined.
printSquare(size):
- A colon is only required in a function definition. It will cause an error with a function call.
Checkpoint 8.1.10.
True or false: A function can be called several times by placing a function call in the body of a loop.
True
- Yes, you can call a function multiple times by putting the call in a loop.
False
- One of the purposes of a function is to allow you to call it more than once. Placing it in a loop allows it to executed multiple times as the body of the loop runs multiple times.
You have attempted
of
activities on this page.