Programming in Python / Functions
Functions
All 5 lessons, in order.
The unit at a glance
- Give a repeated task a name
A recipe card titled Tea sits in a kitchen drawer.
- Pass an argument
A printed invitation leaves a blank after the word Dear.
- Return a result
A shop has a price board on the wall and a clerk with a calculator.
- Trace a local name
A workshop lends each visitor a tray of tools at the door.
- Compose two small functions
A stall at a market works out a bill in three small jobs.
Rules (5)
- Give a repeated task a name
A
defline and its indented body define a function without running the body. The functions of this lesson have no parameters. Once such a function has been defined, a call, written as its name followed by an empty pair of parentheses, runs the body from its first line. When the body finishes, the program carries on from the place of the call. Each such call runs the body once. - Pass an argument
A parameter is a name in the parentheses of a
defline, and an argument is a value in the parentheses of a call. For the calls in this unit, Python works out the arguments, ties them to the parameters in order and then runs the body. For the functions defined in this unit, a call with fewer arguments than parameters stops with a TypeError. - Return a result
A
returnline works out its expression, ends the call and gives that value back to the calling line; areturnwith no expression gives backNone. A call whose body runs to its end without reaching areturnline gives backNone, and that includes a body that prints its result. - Trace a local name
A parameter, and any name assigned anywhere in a function's body, is local to one call of that function. A name that is neither a parameter nor assigned in the body is looked up among the global names, and after those among Python's built-in names. An assignment in the body makes or changes a local name and leaves a global name of the same spelling as it was. Outside the function the local names do not exist.
- Compose two small functions
Python works out every argument of a call before the call begins. When an argument is itself a call, that call finishes first and its return value becomes the argument of the call that receives it. For the receiving call to get a value other than
None, the inner function has to return one.
Recipes (5)
- Give a repeated task a name
- Find the lines that the program needs in more than one place.
- Write
def, a name that says what the lines do, an empty pair of parentheses and a colon. - Put the lines under the
defline and indent them one more level, four spaces, keeping any deeper indentation they already have. - Leave the indented block, and write the function's name with parentheses at each place where the lines should run.
- Trace the program: skip the body at the
defline, and run the body at each call.
- Pass an argument
- Find the value in the body that should change from call to call.
- Give that value a name and write the name inside the parentheses of the
defline. For two values, write two names with a comma between them. - Use the names in the body where the values were.
- In each call, write the values inside the parentheses in the same order as the names.
- Trace a call by writing each parameter with the argument it received, then running the body with those values.
- Return a result
- Decide what value the rest of the program needs from the function.
- Write
returnfollowed by that value, or by the expression that works it out, at each point where the function's work is done. In the first worked example that is the last line of the body. - At the call, do something with the value: give it a name, print it or use it in an expression.
- Trace a call by replacing it with the value it returns, then finishing the line the call was in.
- If a function should only display something, leave
returnout and call it on a line of its own.
- Trace a local name
- Draw two columns for names: one for the file's global names and one for the call's local names.
- At a call, start a fresh local column and write each parameter in it with the argument it received.
- When the body uses a parameter or a name that it assigns, read it from the local column. If that local name has no value yet on that line, the program stops with an UnboundLocalError. For any other name, read the global column, and after that Python's built-in names such as
print. - At an assignment inside the body, first work out the right side, reading each name as the step before says. Then write or change the name on the left in the local column. Leave the global column alone.
- At a return line, work out the value to give back while the local column is still there.
- When the call ends, cross out the whole local column. If the rest of the program needs the returned value, give it a name at the call.
- Compose two small functions
- Write the task as a list of small jobs, each one taking some values and giving one value back.
- Write one function for each job, with a parameter for each value it takes. Return its result.
- Test each function that calls no other function alone, with a few arguments, including any boundary value. Compare with results worked out by hand.
- Join the functions by passing one call as the argument of another, or by giving a result a name and passing the name. Then test the joined function in the same way.
- Trace a joined line by working out each argument before the call that receives it, and replace each finished call with the value it returns.
Traps (5)
- Give a repeated task a name
The parentheses make the call. On a line below the function's definition, the name alone,
show_bannerwith no parentheses, does not call it. The file displays no banner and reports no error. Check for the parentheses when a function seems to do nothing.The body belongs to the function only while it is indented. A print line at the margin, after the body, is not part of the function. It runs once, when Python reaches it, and not at each call.
- Pass an argument
Arguments in the wrong order are the quiet mistake.
label(3, "pens")is a legal call, and the program displayspens x 3. Check each call against the order of the names in thedefline.A second slip is to put quotation marks around a parameter's name in the body. Quotation marks make text, so
print("name")displays the word name for every guest. Write the name without quotation marks, or inside the braces of an f-string, to use the value it holds. - Return a result
Printing inside a function is not returning. A function whose body prints its result and has no
returnline gives backNone. A line such astotal = show_double(5) + 1then displays 10 and stops with a TypeError when Python tries to addNoneand 1. A TypeError is the error for an operation applied to a value of the wrong type. Usereturnwhen the calling line needs the value.The opposite slip is to return a value and drop it. A line that holds only
total_price(4, 3)runs the function, and in a file that is run it displays nothing. Python writes out the value of such a line only when the line is typed in the Shell and the value is notNone. - Trace a local name
The common surprise is expecting an assignment inside a function to change a global name. In the counter program the global
countstill holds5afterreset()has run. To change a value for the rest of the program, have the function return the new value and assign it at the call. With aresetwhose body ends inreturn 0, the linecount = reset()gives the globalcountthe value0.A sharper form of the same slip is a line such as
count = count + 1inside a function, withcountassigned only at the margin. The assignment makescountlocal, so the right side asks for a local name that has no value yet, and the program stops with an UnboundLocalError, which is a kind of NameError. Pass the value in as an argument and return the result. - Compose two small functions
A function that prints where it should return breaks the chain. If
subtotaldisplayed the product and had noreturnline,with_feewould receiveNone. The comparisonNone < 20would then stop the program with a TypeError, because Python provides no order comparison betweenNoneand a number. Return from every function whose value another function needs.The other slip is one long function that does every job. Split it where one value is finished and the next job begins, so that each job can be called and tested by its own name.
Lesson 1 of 5
Give a repeated task a name
Open this lessonLeans on 1Comes back in 0
Leans on
Comes back in
No lesson links recorded.
1 In plain words
A recipe card titled Tea sits in a kitchen drawer. Writing the card makes no tea. When someone says to make tea, the cook takes out the card and follows its steps, and the card is there again the next time.
A function is a block of lines with a name. A def line starts it: the word def, the function's name, a pair of parentheses and a colon. The indented lines under it are the function's body.
Defining a function does not run its body. The body runs when the defined function is called, and it runs again at every such call. In this lesson a call to one of your own functions is its name followed by an empty pair of parentheses, such as show_banner().
Remember one sentence: def writes the card, and a call follows it. To look it up, see section 4.8 of the Python 3.13 tutorial, on defining functions.
2 Picture it
A table of three parts of a program and what each does. The def line names the body. The body waits to be run. A call runs the body. The row for the call is marked.
3 Why
Python reads a file from the top. When it reaches a def line it stores the body under the function's name and moves on to the first line after the body. Nothing is displayed, because the body has not run.
At a call of a function that has been defined, Python goes to the stored body, runs its lines in order and then carries on from the place of the call. The banner program calls show_banner twice, so the three lines of its body run twice.
A name has to have a value before it is used. In a file where nothing else has defined show_banner, a call that runs before the def line stops the program with a NameError.
4 The rule
A def line and its indented body define a function without running the body.
The functions of this lesson have no parameters. Once such a function has been defined, a call, written as its name followed by an empty pair of parentheses, runs the body from its first line. When the body finishes, the program carries on from the place of the call. Each such call runs the body once.
5 How
- Find the lines that the program needs in more than one place.
- Write
def, a name that says what the lines do, an empty pair of parentheses and a colon. - Put the lines under the
defline and indent them one more level, four spaces, keeping any deeper indentation they already have. - Leave the indented block, and write the function's name with parentheses at each place where the lines should run.
- Trace the program: skip the body at the
defline, and run the body at each call.
6 Worked example
Call one function twice
def show_banner():
print("============")
print("LOST AND FOUND")
print("============")
show_banner()
print("Blue scarf")
show_banner()
Standard input
Empty
Standard output
============
LOST AND FOUND
============
Blue scarf
============
LOST AND FOUND
============
Predict the seven output lines first. Then save the code as banner.py and run the file, or follow the trace below. The body runs once for each call.
Call the function too early
show_banner()
def show_banner():
print("LOST AND FOUND")
Standard input
Empty
Standard output
Empty
Exception NameError
Save the four lines as early.py and run the file. The call is on line 1, above the def line, so Python does not know the name yet and stops with a NameError. Move the call below the function to repair the program.
Trace
| Instruction | What Python does | Output | Explanation |
|---|---|---|---|
def show_banner(): | Stores the three body lines under the name | — | Nothing is displayed. Python moves to the first line after the body. |
show_banner() | Runs the body | the three banner lines | The first call. The body's three print lines run in order. |
print("Blue scarf") | Runs | Blue scarf | Python has come back from the call and carries on. |
show_banner() | Runs the body again | the three banner lines | The second call runs the same three lines. |
7 The trap
The parentheses make the call. On a line below the function's definition, the name alone, show_banner with no parentheses, does not call it. The file displays no banner and reports no error. Check for the parentheses when a function seems to do nothing.
The body belongs to the function only while it is indented. A print line at the margin, after the body, is not part of the function. It runs once, when Python reaches it, and not at each call.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
def chime():
print("ding")
print("start")
chime()
chime()
print("end")Show the steps and the answer
It displays start, ding, ding and end, each on its own line.
Why: The def line displays nothing. The first print runs, then each call runs the body once, then the last print runs.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.7 Function definitions
Quick check 2 of 2
A file holds only these two lines. What does it display when it is run?
def hello():
print("hello")Show the steps and the answer
It displays nothing.
Why: The file defines the function and never calls it. The body runs only at a call.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.7 Function definitions
Sources
- Python 3.13 Tutorial, 4.8 Defining Functions. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 8.7 Function definitions. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.3.4 Calls. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: NameError. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 7.1 Expression statements. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 2 of 5
Pass an argument
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A printed invitation leaves a blank after the word Dear. The printer makes one design, and each copy gets a different name written into the blank.
A function can have blanks of its own. A parameter is a name written inside the parentheses of the def line. An argument is a value passed to a function in a call. It is written, or worked out from what is written, inside the call's parentheses.
At a call, Python ties each parameter to an argument. With the calls in this unit the order decides: the first argument goes to the first parameter, the second to the second. Inside the body, a parameter is used like any other name.
Remember one sentence: the parameter is the blank, and the argument is what fills it. To look them up, find parameter and argument in the glossary of the Python 3.13 documentation.
2 Picture it
A table for the call label("pens", 3). The first position ties the parameter item to the argument "pens". The second position ties the parameter count to the argument 3. The first row is marked.
3 Why
One function can serve many values because the body is written with names, and each call says what the names hold this time. The line greet("Ada") runs the body with name holding "Ada", and greet("Sam") runs the same body with name holding "Sam".
Python works out each argument before the call begins. In label("cups", 2 + 2) the addition is done first, and the parameter count receives 4.
A call has to supply an argument for each parameter of the functions in this unit. A call with too few stops the program with a TypeError.
4 The rule
A parameter is a name in the parentheses of a def line, and an argument is a value in the parentheses of a call.
For the calls in this unit, Python works out the arguments, ties them to the parameters in order and then runs the body. For the functions defined in this unit, a call with fewer arguments than parameters stops with a TypeError.
5 How
- Find the value in the body that should change from call to call.
- Give that value a name and write the name inside the parentheses of the
defline. For two values, write two names with a comma between them. - Use the names in the body where the values were.
- In each call, write the values inside the parentheses in the same order as the names.
- Trace a call by writing each parameter with the argument it received, then running the body with those values.
6 Worked example
Greet two guests with one function
def greet(name):
print(f"Welcome, {name}")
greet("Ada")
greet("Sam")
Standard input
Empty
Standard output
Welcome, Ada
Welcome, Sam
Predict the two output lines first. Then save the code as greet.py and run the file. Each call ties the parameter name to its own argument.
Pass two arguments in order
def label(item, count):
print(f"{count} x {item}")
label("pens", 3)
label(3, "pens")
Standard input
Empty
Standard output
3 x pens
pens x 3
Predict the two output lines first. Then save the code as label.py and run the file. The second call gives the arguments in the other order, so item holds 3 and count holds the text. Python reports no error, and the label comes out the wrong way around.
Leave an argument out
def greet(name):
print(f"Welcome, {name}")
greet()
Standard input
Empty
Standard output
Empty
Exception TypeError
Save the four lines as missing.py and run the file. The call supplies no argument for name, so Python stops with a TypeError before the body runs.
Trace
| Instruction | item | count | Output | Explanation |
|---|---|---|---|---|
def label(item, count): | unset | unset | — | The def line stores the body. The parameters hold nothing yet: they get values at a call. |
label("pens", 3) | "pens" | 3 | — | The first argument goes to item and the second to count. |
print(f"{count} x {item}") | "pens" | 3 | 3 x pens | The body runs with those two values. |
7 The trap
Arguments in the wrong order are the quiet mistake. label(3, "pens") is a legal call, and the program displays pens x 3. Check each call against the order of the names in the def line.
A second slip is to put quotation marks around a parameter's name in the body. Quotation marks make text, so print("name") displays the word name for every guest. Write the name without quotation marks, or inside the braces of an f-string, to use the value it holds.
Quick checks
Quick check 1 of 2
The label program defines label(item, count) as in the worked example. What does this call display?
label("cups", 2 + 2)Show the steps and the answer
It displays 4 x cups.
Why: Python works out 2 + 2 before the call, so count receives 4, and item receives the text cups.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.3.4 Calls
Quick check 2 of 2
Predict what this program displays. The program reads no input.
def seat(row, number):
print(f"Row {row}, seat {number}")
seat(7, 2)
seat(2, 7)Show the steps and the answer
It displays Row 7, seat 2 and then Row 2, seat 7.
Why: The first argument of each call goes to row and the second to number. The two calls give the same numbers in different orders.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.3.4 Calls
Sources
- Python 3.13 Glossary: parameter. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Glossary: argument. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.3.4 Calls. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 3.1.2 Text. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 3 of 5
Return a result
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A shop has a price board on the wall and a clerk with a calculator. The board shows a number to anyone who looks. The clerk works out a number and hands it to you on a slip, and you can add it to your own sums.
print is the board: it displays a value for a person to read. A return line is the clerk. It ends the call and hands a value back to the line that made the call. That value is the function's return value.
A call that returns a value can stand wherever a value can. The program can give it a name, print it or use it in a calculation.
A function that reaches the end of its body without a return line still gives something back: the value None, which stands for nothing.
Remember one sentence: print shows a value, and return hands it back. To look it up, see section 7.6 of the Python 3.13 language reference, on the return statement.
2 Picture it
A table of two calls. The call show_double(5) displays 10 and gives back None. The call give_double(5) displays nothing and gives back 10. The row for give_double is marked.
3 Why
When Python reaches a return line it works out the expression after the word return, leaves the function at once and puts that value where the call was. A return with nothing after it gives back None. In bill = total_price(4, 3) the call becomes 12, and the name bill is tied to 12.
Because return leaves the function, no later line of the body runs in that call. A function can hold more than one return line, and the first one Python reaches ends the call.
A call that finishes normally gives some value back. When the body has no return line, that value is None.
4 The rule
A return line works out its expression, ends the call and gives that value back to the calling line; a return with no expression gives back None.
A call whose body runs to its end without reaching a return line gives back None, and that includes a body that prints its result.
5 How
- Decide what value the rest of the program needs from the function.
- Write
returnfollowed by that value, or by the expression that works it out, at each point where the function's work is done. In the first worked example that is the last line of the body. - At the call, do something with the value: give it a name, print it or use it in an expression.
- Trace a call by replacing it with the value it returns, then finishing the line the call was in.
- If a function should only display something, leave
returnout and call it on a line of its own.
6 Worked example
Use a returned price twice
def total_price(price, count):
return price * count
bill = total_price(4, 3)
print(bill)
print(total_price(2, 5) + 1)
Standard input
Empty
Standard output
12
11
Predict the two output lines first. Then save the code as price.py and run the file, or follow the trace below. Each call is replaced by the value it returns.
Print in one function and return from another
def show_double(n):
print(n * 2)
def give_double(n):
return n * 2
result = show_double(5)
print(result)
print(give_double(5))
Standard input
Empty
Standard output
10
None
10
Predict the three output lines first. Then save the code as double.py and run the file. The body of show_double displays 10. It has no return line, so the call gives back None, and that is what the second output line shows. give_double displays nothing itself. It returns 10, and the last line prints that value.
Leave a function at the first return
def late_fee(days):
if days == 0:
return 0
return 2
print(late_fee(0))
print(late_fee(4))
Standard input
Empty
Standard output
0
2
Predict the two output lines first. Then save the code as fee.py and run the file. For 0 days the condition is True and the first return line ends the call, so the second is never reached. For 4 days the condition is False, the indented block is skipped and the call ends at the second return line.
Trace
| Instruction | Call becomes | Output | Explanation |
|---|---|---|---|
def total_price(price, count): | — | — | The def line stores the body. |
bill = total_price(4, 3) | 12 | — | The call ties price to 4 and count to 3. The return line gives back 4 * 3. bill now names 12. |
print(bill) | — | 12 | The value the function returned is displayed. |
print(total_price(2, 5) + 1) | 10 | 11 | The call is worked out first and gives back 10. Then 10 + 1 is worked out and displayed. |
7 The trap
Printing inside a function is not returning. A function whose body prints its result and has no return line gives back None. A line such as total = show_double(5) + 1 then displays 10 and stops with a TypeError when Python tries to add None and 1. A TypeError is the error for an operation applied to a value of the wrong type. Use return when the calling line needs the value.
The opposite slip is to return a value and drop it. A line that holds only total_price(4, 3) runs the function, and in a file that is run it displays nothing. Python writes out the value of such a line only when the line is typed in the Shell and the value is not None.
Quick checks
Quick check 1 of 2
Predict the two lines this program displays. The program reads no input.
def area(width, height):
return width * height
print(area(3, 4))
print(area(2, 2) + area(1, 5))Show the steps and the answer
It displays 12 and then 9.
Why: The first call returns 3 * 4. In the second line the calls return 4 and 5, and 4 + 5 is 9.
Source: Python Software Foundation, Python 3.13 Language Reference, 7.6 The return statement
Quick check 2 of 2
What does this program display, and why is the second line not a number?
def show_sum(a, b):
print(a + b)
answer = show_sum(2, 3)
print(answer)Show the steps and the answer
It displays 5 and then None.
Why: The body prints 5. It has no return line, so the call gives back None, and answer names None.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.8 Defining Functions
Sources
- Python 3.13 Language Reference, 7.6 The return statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.3.4 Calls. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.8 Defining Functions. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: TypeError. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 7.1 Expression statements. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 4 of 5
Trace a local name
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A workshop lends each visitor a tray of tools at the door. The visitor uses the tools inside and hands the tray back on the way out. The next visitor gets a fresh tray, and nothing on a tray leaves the workshop.
A function works with names in the same way. A name that gets its value inside a function, including each parameter, is a local name. Each call gets its own set of local names, and they are gone when the call ends.
A name that gets its value in the file's own lines, outside every function, is a global name. A function can read a global name. An assignment inside a function makes a local name, and that is true when a global name of the same spelling exists as well.
Remember one sentence: a name assigned inside a function lives and ends with one call. To look it up, see section 4.2 of the Python 3.13 language reference, on naming and binding.
2 Picture it
A table of two names that are both spelled count. The local count holds 0 inside the function reset and is gone after the call. The global count is not changed inside reset and holds 5 after the call. The row for the global name is marked.
3 Why
Python decides which names are local to a function from its definition, before any call runs: the parameters named in the def line and every name the body assigns. At the start of each call the parameters get their values, and each other local name has no value until its assignment line runs. When the body uses a parameter or a name that it assigns anywhere in the body, even on a line above the assignment, Python uses the local name. For any other name it looks among the global names, and after those among Python's built-in names, which is where print is found.
That order explains the counter program. Inside reset, the line count = 0 makes a local count. The print line in the body uses that local name and displays 0. The global count was never touched, so the last line of the file displays 5.
When the call ends, its local names end with it. A line outside every function cannot reach them: Python looks for the name among the global names and then the built-in names, and if neither has that spelling, the program stops with a NameError. Another function that has the same spelling as a parameter, or assigns it, gets a local name of its own. One that does neither looks among the global and built-in names, and stops with a NameError when neither has it. Either way it never reaches this call's local name.
4 The rule
A parameter, and any name assigned anywhere in a function's body, is local to one call of that function.
A name that is neither a parameter nor assigned in the body is looked up among the global names, and after those among Python's built-in names. An assignment in the body makes or changes a local name and leaves a global name of the same spelling as it was. Outside the function the local names do not exist.
5 How
- Draw two columns for names: one for the file's global names and one for the call's local names.
- At a call, start a fresh local column and write each parameter in it with the argument it received.
- When the body uses a parameter or a name that it assigns, read it from the local column. If that local name has no value yet on that line, the program stops with an UnboundLocalError. For any other name, read the global column, and after that Python's built-in names such as
print. - At an assignment inside the body, first work out the right side, reading each name as the step before says. Then write or change the name on the left in the local column. Leave the global column alone.
- At a return line, work out the value to give back while the local column is still there.
- When the call ends, cross out the whole local column. If the rest of the program needs the returned value, give it a name at the call.
6 Worked example
Assign a name that also exists outside
count = 5
def reset():
count = 0
print(count)
reset()
print(count)
Standard input
Empty
Standard output
0
5
Predict the two output lines first. Then save the code as counter.py and run the file, or follow the trace below. The assignment in the body makes a local name, and the global name keeps its value.
Use a local name outside its function
def add_tip(bill):
tip = 2
return bill + tip
print(add_tip(10))
print(tip)
Standard input
Empty
Standard output
12
Exception NameError
Predict what happens on each of the last two lines first. Then save the code as tip.py and run the file. The call returns 12, which is displayed. The last line asks for tip outside the function, where no such name exists, and the program stops with a NameError.
Read a global name inside a function
rate = 3
def cost(hours):
return hours * rate
print(cost(4))
Standard input
Empty
Standard output
12
Predict the output line first. Then save the code as rate.py and run the file. The body assigns nothing to rate, so Python finds no local name of that spelling and uses the global one.
Trace
| Instruction | Global count | Local count | Output | Explanation |
|---|---|---|---|---|
count = 5 | 5 | none | — | An assignment at the margin makes a global name. |
def reset(): | 5 | none | — | The def line stores the body. No local name exists yet. |
reset() | 5 | no value yet | — | The call starts. count is local to reset, because the body assigns it, but it has no value until that line runs. |
count = 0 | 5 | 0 | — | The assignment in the body makes a local count. The global count stays 5. |
print(count) | 5 | 0 | 0 | The body assigns count, so this line uses the local count. |
print(count) | 5 | none | 5 | The call has ended and its local name is gone. This line is at the margin, so it uses the global count. |
7 The trap
The common surprise is expecting an assignment inside a function to change a global name. In the counter program the global count still holds 5 after reset() has run. To change a value for the rest of the program, have the function return the new value and assign it at the call. With a reset whose body ends in return 0, the line count = reset() gives the global count the value 0.
A sharper form of the same slip is a line such as count = count + 1 inside a function, with count assigned only at the margin. The assignment makes count local, so the right side asks for a local name that has no value yet, and the program stops with an UnboundLocalError, which is a kind of NameError. Pass the value in as an argument and return the result.
Quick checks
Quick check 1 of 2
Predict the two lines this program displays. The program reads no input.
color = "white"
def paint():
color = "green"
print(color)
paint()
print(color)Show the steps and the answer
It displays green and then white.
Why: The assignment in the body makes a local color, and the print line in the body uses it. The global color is not changed, and the last line displays it.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.8 Defining Functions
Quick check 2 of 2
This program stops with an error on its last line. Which name causes it, and what one change to the last two lines displays 9?
def add(a, b):
total = a + b
return total
add(4, 5)
print(total)Show the steps and the answer
The name total causes it, because total is local to add. Give the returned value a name at the call and print that name: result = add(4, 5) and then print(result).
Why: total exists only during the call. The call returns 9, and a name assigned at the margin can hold that value for the last line.
Source: Python Software Foundation, Python 3.13 Language Reference, 4.2 Naming and binding
Sources
- Python 3.13 Tutorial, 4.8 Defining Functions. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 4.2 Naming and binding. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 5 of 5
Compose two small functions
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A stall at a market works out a bill in three small jobs. One person multiplies the price by the number of items. A second adds a bag fee to a small order. A third writes the line on the receipt. Each person can be checked alone, and the bill passes from one to the next.
A program can be split the same way. Breaking a task into small functions, each with one job, is called decomposition. Using one function's return value as another function's argument is called composition. Those two words are this lesson's own shorthand, and the rule that makes composition work is Python's: every argument is worked out before the call it belongs to begins.
The stall's rule is invented for this lesson, and the receipt program below follows it. The bill is the price times the count. A bill under 20 coins gets a bag fee of 3 coins, and a bill of 20 or more gets none. The function with_fee returns from inside an if block for the small bill and from the line after it for the rest.
Remember one sentence: a call used as an argument finishes first, and its value becomes the argument. To look it up, see section 6.3.4 of the Python 3.13 language reference, on calls.
2 Picture it
A table of three calls and what each gives back. subtotal(4, 3) gives back 12. with_fee(12) gives back 15. receipt(4, 3) gives back the text Total: 15 coins. The row for receipt is marked.
3 Why
In with_fee(subtotal(price, count)), the argument of with_fee is itself a call. Python works out an argument before it makes the call that uses it, so subtotal runs first and its return value is passed to with_fee.
Composition needs return values. A function that prints its result and has no return line gives back None, and the next function would receive None in place of a number.
Small functions can be tested one at a time. By the stall's rule above, with_fee has a boundary at 20: its if takes one branch for 19 and the other for 20. Those two values test it without any price or count. Test each part alone first. If the receipt is still wrong, look next at the way the parts are joined, and at inputs that no test tried.
4 The rule
Python works out every argument of a call before the call begins.
When an argument is itself a call, that call finishes first and its return value becomes the argument of the call that receives it. For the receiving call to get a value other than None, the inner function has to return one.
5 How
- Write the task as a list of small jobs, each one taking some values and giving one value back.
- Write one function for each job, with a parameter for each value it takes. Return its result.
- Test each function that calls no other function alone, with a few arguments, including any boundary value. Compare with results worked out by hand.
- Join the functions by passing one call as the argument of another, or by giving a result a name and passing the name. Then test the joined function in the same way.
- Trace a joined line by working out each argument before the call that receives it, and replace each finished call with the value it returns.
6 Worked example
Join three functions into a receipt
def subtotal(price, count):
return price * count
def with_fee(amount):
if amount < 20:
return amount + 3
return amount
def receipt(price, count):
total = with_fee(subtotal(price, count))
return f"Total: {total} coins"
print(receipt(4, 3))
print(receipt(6, 5))
Standard input
Empty
Standard output
Total: 15 coins
Total: 30 coins
Predict the two output lines first. Then save the code as receipt.py and run the file, or follow the trace below. In each call of receipt, subtotal runs before with_fee.
Test one function alone at its boundary
def with_fee(amount):
if amount < 20:
return amount + 3
return amount
print(with_fee(19))
print(with_fee(20))
Standard input
Empty
Standard output
22
20
Predict the two output lines first. Then save the code as fee_test.py and run the file. 19 is under 20, so the fee is added. 20 is not under 20, so the indented return line is skipped and the amount comes back unchanged.
Trace
| Call | Arguments | Gives back | Explanation |
|---|---|---|---|
receipt(4, 3) starts | price 4, count 3 | — | The body of receipt begins. Its first line holds two more calls. |
subtotal(price, count) | 4 and 3 | 12 | This call is an argument of with_fee, so it finishes first: 4 * 3 is 12. |
with_fee(12) | 12 | 15 | By the stall's rule, 12 is under 20, so the fee of 3 is added and 15 comes back. total now names 15. |
receipt(4, 3) ends | — | Total: 15 coins | The return line builds the text and gives it back to the print call, which displays it. |
7 The trap
A function that prints where it should return breaks the chain. If subtotal displayed the product and had no return line, with_fee would receive None. The comparison None < 20 would then stop the program with a TypeError, because Python provides no order comparison between None and a number. Return from every function whose value another function needs.
The other slip is one long function that does every job. Split it where one value is finished and the next job begins, so that each job can be called and tested by its own name.
Quick checks
Quick check 1 of 2
Using the receipt program from the worked example, what does print(receipt(5, 4)) display? Name the value each of the two inner calls gives back.
Show the steps and the answer
It displays Total: 20 coins. subtotal(5, 4) gives back 20, and with_fee(20) gives back 20.
Why: 5 * 4 is 20. 20 is not under 20, so no fee is added, and the receipt line is built from 20.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.3.4 Calls
Quick check 2 of 2
Predict the two lines this program displays. The program reads no input.
def triple(n):
return n * 3
def add_ten(n):
return n + 10
print(add_ten(triple(4)))
print(triple(add_ten(4)))Show the steps and the answer
It displays 22 and then 42.
Why: In the first line the call triple(4) is an argument, so it finishes first and gives back 12, and add_ten(12) gives back 22. In the second line add_ten(4) gives back 14, and triple(14) gives back 42.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.3.4 Calls
Sources
- Python 3.13 Language Reference, 6.3.4 Calls. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 7.6 The return statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.8 Defining Functions. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.10.1 Value comparisons. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: TypeError. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.