Writing the same lines again
Every program you have written so far runs each of its lines once, from the top down. Real programs often need the same steps more than once. Say you are writing a quiz that prints two lines of instructions before each of its three questions. With what you know so far, you have to write those two lines out three times:
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 1: 6 * 7")
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 2: 9 - 13")
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 3: 15 % 4")This works until the instructions change. If the time limit becomes 20 seconds, you have to edit every copy, and if you miss one, the quiz tells the player two different limits.
Often the copies are not even identical. Suppose each round gets shorter: 30 seconds for the first question, 20 for the second and 10 for the third. Now the copies differ in one number, and you still write each one out by hand.
We want to write the two lines once, give them a name, and run them by that name wherever the quiz needs them, with a different number each time. A function lets you do that. Another way to repeat lines is the loop, which suits steps that run one after another; here the instructions are spread between the questions, so a function fits better.
The quiz instructions as a function
Here is the quiz with a function. The two lines are written once, under the name instructions, and the number of seconds, which is different in each round, gets a name of its own, seconds:
def instructions(seconds):
print("Answer with one number.")
print("You have", seconds, "seconds.")
instructions(30)
print("Question 1: 6 * 7")
instructions(20)
print("Question 2: 9 - 13")
instructions(10)
print("Question 3: 15 % 4")The first three lines are the function definition. def instructions(seconds): says that a function named instructions starts here, and the indented lines under it are its body. Defining the function prints nothing. The body runs when you call the function by writing its name and parentheses, as in instructions(30), the same way you called abs and max. seconds is a parameter: a name for the value that changes from call to call. The 30 in instructions(30) is that call's argument, so while that call runs, seconds is 30, and during the next call it is 20.
The program prints the nine lines of the quiz, now with limits of 30, 20 and 10 seconds. The instructions are written once, so if their wording changes, you edit one place.
Definition
A function definition gives a name to a block of code and lists its parameters. A call runs the block, with each parameter holding the matching argument.
Functions that return a value
instructions does its job by printing. Most functions work out a value instead and hand it back, the way abs and max do, so that the call can be used inside a bigger expression. A function hands a value back with return. Here is a function that squares a number, called three times:
def square(x):
return x * x
print(square(5))
print(square(1 + 2))
print(square(square(2)))Python details
The code gives x no type, unlike the C++ version. Python checks the type only when x * x runs, and stops with a TypeError if x is a value that cannot be multiplied.
return x * x works out the square, sends it back to the call and ends the call; any lines after it in the body would not run.
An argument can be any expression, and it is evaluated before the function receives it. square(1 + 2) receives 3, and square(square(2)) first works out square(2), which is 4, and then squares that.
square(5) evaluates to 25 and can stand anywhere a number can, just as abs(-5) can.
Function names and signatures
When Python reaches the def line, it cannot run the body yet: there is no x to square until something calls square.
Instead, Python keeps the parameter list and the body together as a function object, and binds the name square to it in the frame, the same way = binds a name to a number. After the def line, the global frame holds the name square, just as the payroll program's frame held pay. It is an ordinary binding, so a later def or = that uses the name square replaces it.
The list of parameters on the def line is the function's signature, and it fixes how many arguments a call must pass. square has one parameter, so square(1, 2) stops the program with TypeError: square() takes 1 positional argument but 2 were given.
Calling a user-defined function
A program with functions has two kinds of names: the ones it binds outside any function, such as x = 10, and the parameters of each function. What if both use the same name? If the program has its own x and calls square(3), which x does x * x mean inside the body? To answer that, you need to see what Python sets up when a call runs. The programs so far had one frame, the global frame, which holds every name the program binds. Calling a function you defined adds a second frame. A call such as square(1 + 2) runs in three steps:
- The program finds the function named
squareand works out each argument:1 + 2becomes 3. - A new local frame is created for this call, and each parameter is bound to its argument in it:
xto 3. - The body runs. When it reaches
return, the returned value becomes the value of the call, and the local frame is thrown away.
While the body runs, Python looks up each name in the call's local frame first. If the name is not there, Python looks in the global frame, and after that among its built-in names such as max and abs. It uses the first binding it finds. So inside square, x means the parameter, because the local frame is searched first. The frames a call searches, in that order, are called its environment.
The demo below is the same kind of step-through as the payroll one, now with more than one frame. Its program defines sum_squares(a, b), which returns square(a) + square(b), so one call to sum_squares makes two calls to square. Watch each frame open when its call starts and close when it returns.
Step through a call
At the step where square(3) is running, three frames exist at once: the global frame, the one for sum_squares and the one for square. sum_squares has stopped partway through its line, and it carries on once square returns 9. Each function object is drawn with [parent=Global], the frame a call falls back to when a name is not local.
The second call to square gets a fresh frame of its own, so the x bound to 3 and the x bound to 4 sit in different frames. Equal arguments still get separate frames: sum_squares(5, 5) draws two square frames, both with x bound to 5.
The frames of calls that have not returned yet form the call stack. Each call puts its frame on top, and a returning call takes its frame off again, so the frame on top always belongs to the call that is running now.
Nested calls
square(square(2)) put one call inside another. Calls can be nested much deeper than that, and the rule stays the same: the innermost call runs first, all the way to its return, and only its value is passed outward. Here is an AtCoder problem that is nothing but nested calls:
Let . Given an integer , print the value of . The answer is guaranteed to be at most .
Constraints
- is an integer, given on one line.
Sample 1 · Input
0
Output
1371
Sample 2 · Input
3
Output
722502
Sample 3 · Input
10
Output
1111355571
If you wrote this out without a function, would appear five times, each copy with a different expression in place of . That is the quiz problem again, copies that differ in one value, packed into one formula, and a slip in any copy gives a wrong answer. With a function, you write once, as f, and then type the expression exactly as the statement writes it.
For the first sample, , work from the inside out. , so is 3, and . The other half of the sum, , is also . The outermost call receives :
def f(x):
return x * x + 2 * x + 3
t = int(input())
print(f(f(f(t) + t) + f(f(t))))The program calls f five times, so five local frames are created, yet no two f frames exist at the same moment. Each argument is finished before the call that receives it begins, so every inner frame has closed by the time the outer one opens. sum_squares was different: it called square from inside its body, so its frame stayed open while square ran.
Names in functions
A body can use a name that is not one of its parameters. Here with_tax adds a sales tax of rate percent to a price, and rate is bound in the global frame. Step through to see where each name is found.
With a price of 250, price is found in f1 and rate in the global frame, and the call returns . With 99, the tax is , since // drops the fraction of 7.92, so the call returns 106.
The third preset rebinds rate to 10 after the def and before the call, and the call returns 275 instead of 270. A body's names are looked up when the function is called, with whatever they are bound to at that moment.
Local names
Here the program has an x of its own, and square has a parameter named x too:
x = 10
def square(x):
return x * x
print(square(3))
print(x)The program prints 9 and then 10. The call binds its own x to 3 in its local frame, and inside the body the lookup finds that x before it reaches the global frame. The parameter shadows the global x: the global one still holds 10, but the body cannot see it under that name. An assignment such as x = 0 inside the body would also bind only the local x, and the global x would stay 10.
A name bound in one call's frame is a local name. It exists only while that call runs, and code outside the call can neither read it nor change it.
Because a parameter exists only inside its call, you can rename it and the calls stay the same. Rewritten as def square(n): return n * n, square(3) still returns 9. The part of a program where a name can be used is its scope, and the scope of a parameter is the body of its function.
Choosing names
Python and C++ do not care what you call a function or a parameter, so choose names for the people who read the code. area(width, height) in the middle of a line says what it computes; with f(a, b), the reader has to find the definition of f.
Name a function after the value it returns, as with square and area, and a parameter after what it holds. Short names such as t and x are fine when the problem statement uses them, as Weird Function does. Python writes function and parameter names in lowercase with _ between words, as its PEP 8 style guide recommends.
| Name | What a reader can tell | Better |
|---|---|---|
f(a, b) | Only that it takes two values. | area(width, height) |
calc(x) | It works something out from x. | square(x) |
with_tax(p) | It adds tax to something, but p could be a price or a percentage. | with_tax(price) |
l = 1 | In many fonts l and I look like 1, and O looks like 0. | length = 1 |
A def is a binding, so a function you name max, sum or print hides the built-in one, the way max = 10 hides the built-in max. A name of your own, such as largest, avoids the problem.
Functional abstraction
Look again at sum_squares. It uses the value square returns and nothing about how square works it out. So you could give square a different body, and as long as it returned the same values, sum_squares would never notice. Here are two perimeter functions whose bodies differ:
def perimeter_add(width, height):
return width + width + height + height
def perimeter_double(width, height):
return 2 * (width + height)
print(perimeter_add(3, 4), perimeter_double(3, 4))
print(perimeter_add(0, 5), perimeter_double(0, 5))For every width and height the two return the same number, so a program could call either one and print the same output. When you write the caller, you can think of the perimeter as one step and forget how it is worked out. Using a function this way, through what it takes and returns and never through its body, is called functional abstraction. You have used max and abs like this all along, without ever seeing their bodies.
A caller needs to know three facts about a function: which arguments it accepts, called its domain (here, two lengths of 0 or more); which values can come back, its range (a length of 0 or more); and what it does with each argument, its behavior, which includes anything it prints (here, it returns twice the sum and prints nothing).
Printing versus returning
Printing its lines was the whole job of instructions. A function whose job is to work out a value should return it instead. You met this difference with print and abs, and it holds for your own functions too. On the screen the two look the same, but only a returned value can be used by another line:
def square(x):
return x * x
def show_square(x):
print(x * x)
print(square(3) + square(4))
print(show_square(3) + show_square(4))The first sum works, because square hands its result back:
show_square has no return, so a call to it evaluates to None, as a call to print does. The program prints 25 from the first sum, then 9 and 16 while making the two show_square calls, and stops with a TypeError at the addition of two None values.
Composing functions
A function you write can call other functions you wrote, the way sum_squares called square. Building a function out of others is called composition, and it keeps each function short. This problem needs and , and is times :
Given an integer , print as an integer. An output such as 14.0 is judged wrong.
Constraints
- is an integer, given on one line.
Sample 1 · Input
2
Output
14
Sample 2 · Input
10
Output
1110
For the first sample, . The program writes as square(a) and as cube(a), and cube is built from square:
def square(x):
return x * x
def cube(x):
return square(x) * x
a = int(input())
print(a + square(a) + cube(a))cube(2) calls square(2), which returns 4, and multiplies that by 2 to return 8. While square(2) runs, the frame of cube waits beneath it on the call stack, as the frame of sum_squares did.
The statement's warning about 14.0 is the reason cube multiplies instead of calling a power function. a ** 3 is an integer too, but math.pow(a, 3) always returns a float, and 2 + 2 ** 2 + math.pow(2, 3) prints 14.0, the output the statement rejects.
Common mistakes
Forgetting
return.- Where it breaks
- In Python the call evaluates to
None. In C++, a function declared to returnintthat ends withoutreturnhas undefined behavior: it may print garbage or crash. - The fix
- End every path through the function with
returnand the value the caller needs.
Calling a function above its definition.
- Where it breaks
- Python runs a file from the top, so
print(square(3))abovedef squarestops withNameError: name 'square' is not defined. A C++ compiler also reads from the top, and the same call aboveint square(int x)fails to compile: GCC reports'square' was not declared in this scope, and Clanguse of undeclared identifier 'square'. - The fix
- Define each function above the code that calls it. In C++, a declaration such as
int square(int x);abovemainis enough, with the definition later in the file.
Changing a global inside a function (Python).
- Where it breaks
- With
rate = 8at the top, a body containingrate = rate + 1makesratelocal to the whole body, so reading it on the right of the=stops with anUnboundLocalError. In C++ the same line changes the global variable. - The fix
- Pass the value in and return the new one:
def raised(r): return r + 1, called asrate = raised(rate).
Recall How many calls does `sum_squares(3, 4)` make, and how many frames do they create?
Three calls and three new frames, besides the global frame: one for sum_squares and one for each call to square. Calling the same function twice still gives two frames.
Recall Inside `with_tax`, where is `price` found, and where is `rate` found?
price is a parameter, so it is in the call's local frame, the first frame of the environment. rate is not bound there, so the lookup carries on to the global frame and finds it there, with the value it has at the moment of the call.
Key terms
| Term | Meaning |
|---|---|
| function definition | A def block (Python), or a return type, name, parameter list and braced body (C++), that gives a block of code a name and parameters. |
| call | Running a function's body with arguments: instructions(30), square(5). |
| parameter | The name an input has inside the function: x in square(x). |
| argument | The value a call passes in: 5 in square(5). |
| body | The code a function runs on each call. |
| function object (Python) | What a def line creates and binds the function's name to: the parameter list and the body, kept together. |
| signature | The parameters a function takes, which fix what a call must pass. |
| global frame | The frame of names bound outside every function. |
| local frame | The frame a call creates, holding its parameters and the names its body binds. |
| environment | The sequence of frames a name is looked up in, first frame first. |
| call stack | The frames of every call that has not returned yet, newest on top. |
| local name | A name bound in one call's frame, gone when the call returns. |
| shadowing | A local name hiding an outer name of the same spelling inside a body. |
| scope | The part of a program where a name can be used. |
| functional abstraction | Using a function through what it takes and returns, not through its body. |
| domain, range, behavior | The arguments a function accepts, the values it returns, and the result it gives for each argument. |
| composition | Building a function out of calls to other functions, as cube calls square. |
