…
…
Python Programming Fundamentals · Lesson 16 / 40 · Functions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Corner Café's receipt script has grown into a single 15-line block: quantities, prices, the discount rule, and printing are all mixed together. When Ada wanted to change the discount threshold, she had to read all the code to find the right line, and the intern got an error he did not understand at all when he tried to increase the cash register from inside a function. In this lesson you will learn where variables live, and you will split the script into three small functions.
At the end of the lesson you will have a program that prints the same receipt but looks completely different. For 2 lattes, 1 cookie, and 2 teas, the screen will show these three lines:
OutputSubtotal: $13.00
Discount: $1.30
Total due: $11.70The output will stay the same; the layout of the code will change. To get there you need to understand two things: why the names inside a function are not visible from outside, and how to split a big job into small functions.
In this lesson you will:
First, look at how it is today. The script was written with what you learned in lessons 4 and 7: the quantities are in variables, the subtotal is on one line, the discount is in a tiered if/elif/else chain, and the result is printed with f-strings.
Example 1a (case): The long script
# Corner Café receipt script (single block) latte = 2 cookie = 1 tea = 2 subtotal = latte * 4.25 + cookie * 2.00 + tea * 1.25 if subtotal >= 15: discount = subtotal * 15 / 100 elif subtotal >= 10: discount = subtotal * 10 / 100 else: discount = 0 total_due = subtotal - discount print(f"Subtotal: ${subtotal:.2f}") print(f"Discount: ${discount:.2f}") print(f"Total due: ${total_due:.2f}")
OutputSubtotal: $13.00
Discount: $1.30
Total due: $11.70The program works correctly; the problem is reading and changing it. Where does the discount rule start and where does it end? On which line is the latte price? If the number 4.25 ever appears in a second place too, will you remember to change both? As the number of lines grows, these questions get harder to answer. In lesson 14 you moved a repeated calculation into a function. Now we will apply the same idea to the whole program. But first you need to understand how variables inside functions behave; otherwise, while splitting the program you will hit the same error the intern did.
The part of the program from which a name can be seen is called its scope. The rule is two sentences. A function's parameters and the names assigned inside the function are local: they exist only while the function runs, they are deleted when the function ends, and every call creates them from scratch. Names assigned at the top level of the program, that is, outside any function, are global: they live for the whole program and can also be read from inside functions.
Why does this rule exist? Imagine a hundred-line program with ten functions. In every function you use short names like amount, subtotal, and result. If all names were shared, one function could break another function's amount without you knowing. Local scope gives each function its own clean workspace. When you write a function, you do not need to think about which names are used in the rest of the program.
The example below has a global constant and a function. The function reads the global TAX_RATE and also creates an intermediate result called tax_amount inside itself. On the last line we try to print that intermediate result from outside. Read the code first and predict what will happen.
What appears on the screen when this program runs?
TAX_RATE = 0.10 def with_tax(price): tax_amount = price * TAX_RATE return price + tax_amount print(with_tax(10)) print(tax_amount)
Example 2 (case): A function reads a global but does not hand out its locals
TAX_RATE = 0.10 def with_tax(price): tax_amount = price * TAX_RATE return price + tax_amount print(with_tax(10)) print(tax_amount)
On the screen:
Output11.0
Traceback (most recent call last):
File "<code>", line 8, in <module>
print(tax_amount)
^^^^^^^^^^
NameError: name 'tax_amount' is not definedLet's go line by line. On line 1, Python creates the global TAX_RATE. Lines 3–5 only define the function; no calculation happens yet. On line 7, with_tax(10) is called: a local box named price is opened and 10 is put in it. On line 4, TAX_RATE is looked up; it is not in the local scope, so Python looks in the global scope and finds 0.10. So the idea that "a function cannot read a global variable" is wrong: reading is allowed. tax_amount is created as a local and becomes 1.0. return hands 11.0 to the outside and the function ends. At that moment price and tax_amount are deleted. When line 8 looks for tax_amount, there is no such name anymore.
The conclusion: the only correct way to use a value you calculated inside a function outside it is to return it with return and assign the result of the call to a variable. If you needed tax_amount outside too, you would write a separate function that returns it.
Notice the capital letters in TAX_RATE. A value that is set once at the start of the program and never changes afterward is called a constant; in Python, constants are named in capital letters. Python does not actually lock them, but the capital letters tell the reader "do not change this value, only read it." Functions reading a global value is most appropriate for constants like this.
| Local variable | Global variable | |
|---|---|---|
| Where it is created | Inside the function (parameters included) | At the top level |
| Where it can be read | Only from that function | From everywhere |
| When it is deleted | When the function ends | When the program ends |
| Assignment with the same name inside a function | Allowed | Opens a new local variable with the same name; the global does not change |
Now match every name in Example 2 with the correct scope. The function's own name is also like a variable; look at where it is defined.
For each name or line in Example 2, choose the correct match.
For each row, pick its match from the list, then check.
TAX_RATEpricetax_amountwith_tax (the function's name)print(tax_amount) after the function endsprint(TAX_RATE) from inside the functionReading is allowed; but what if you assign to a global name inside a function? Python's rule is this: if a name is assigned anywhere inside a function, Python treats that name as local from the very beginning, before the function starts running. It does not touch the global variable with the same name; inside the function it opens a second, separate box with the same name. That box is also thrown away when the function ends.
Step through the code below. When you enter the function, add() will appear next to the memory heading: the boxes you see at that moment are the function's scratch note. Follow how total becomes 51 inside while the total outside stays 100, and becomes visible again when the function ends. Then use "Change the code" to change the line inside the function to total = total + amount and step through again; you will have seen the answer to the next prediction yourself.
Run the code line by line: see which line runs next, the variable boxes and the output.
total = 100 def add(amount): total = amount + 1 return total result = add(50) print(result) print(total)
The total = amount + 1 inside the function did not change the global total; it opened a new local total. result became 51 because the function returned the local total; the last line printed the global total, and that was always 100. Now let's carry the same idea to the case. Ada has written a function to reset the cash register in the morning.
What does this code print?
register = 25 def start_day(): register = 0 start_day() print(register)
The intern's error is one step beyond this. He wanted to increase the register on every sale and wrote register += amount inside the function. This line actually means register = register + amount: it first reads register, then assigns a new value to it. Because it is an assignment, Python treated register as local from the start. At the moment of reading, the local register box has been opened but it is empty. Predict what will happen before running the code.
What happens when this code runs?
register = 0 def make_sale(amount): register += amount make_sale(4.25) print(register)
Example 3 (case): The broken version first, then the correct one
register = 0
def make_sale(amount):
register += amount
make_sale(4.25)On the screen:
OutputTraceback (most recent call last):
File "<code>", line 6, in <module>
make_sale(4.25)
~~~~~~~~~^^^^^^
File "<code>", line 4, in make_sale
register += amount
^^^^^^^^
UnboundLocalError: cannot access local variable 'register' where it is not associated with a valueThis message has two File lines, because the error happened inside a function. The upper line says "on line 6, make_sale was called"; the lower line says "on line 4 of that function, the error happened." The last line means: "the local variable register cannot be accessed; no value has been bound to it yet." The message clearly says *local*; it is not the global register you were thinking of.
Python has a keyword called global that removes this limit. We do not use it: functions that change global variables from the inside make it very hard to follow where and when a value changes. The right way is this: the function takes the value as a parameter, calculates the new value and returns it; the main code does the assignment.
def make_sale(register, amount): return register + amount register = 0 register = make_sale(register, 4.25) register = make_sale(register, 2.00) print("Register:", register)
OutputRegister: 6.25Read the line register = make_sale(register, 4.25) from right to left: first the value of the global register (0) goes to the function and is put into the function's local register parameter. The function returns 4.25. Then this value is assigned to the global register. On the second sale, the same thing happens with 4.25 and 2.00. The register inside the function and the register outside are still two separate boxes, but now the value is carried from one box to the other on purpose: in with a parameter, out with return. This pattern has one more benefit: you can test the function independently of the register by writing make_sale(10, 5) and checking whether 15 comes back.
Now that you know scope, you are ready to split the receipt script. Splitting a program into functions that each do one job, with names that say that job, is called decomposition. The planning method from lesson 9 works here too:
1. Write the job the program does as steps in plain English: find the subtotal, find the discount, print the receipt.
2. Turn each step into a function. The information the function needs becomes a parameter; the result it produces comes out with return.
3. At the bottom, write a short main code that calls these functions in order.
Follow four rules when splitting. First, a function does one job; if you cannot name it with a single verb or job name, for example if calculate_and_print comes to mind, that function should be split. Second, a function that calculates returns the result, and a function that prints prints; do not mix the two in the same function. Third, values that do not change, like prices, become constants in capital letters at the start of the program, so numbers are not scattered through the code. Fourth, a function can call another function; a big job can be written as a combination of small jobs.
Example 1b (case): The same receipt, three functions
LATTE = 4.25 COOKIE = 2.00 TEA = 1.25 # 1. Find the subtotal def calc_subtotal(latte, cookie, tea): return latte * LATTE + cookie * COOKIE + tea * TEA # 2. Find the discount def calc_discount(amount): if amount >= 15: return amount * 15 / 100 if amount >= 10: return amount * 10 / 100 return 0 # 3. Print the receipt def print_receipt(subtotal, discount): print(f"Subtotal: ${subtotal:.2f}") print(f"Discount: ${discount:.2f}") print(f"Total due: ${subtotal - discount:.2f}") # Main code subtotal = calc_subtotal(2, 1, 2) discount = calc_discount(subtotal) print_receipt(subtotal, discount)
OutputSubtotal: $13.00
Discount: $1.30
Total due: $11.70The output is letter for letter the same as Example 1a. Put Example 1a and 1b side by side: every section in 1a has become a named function in 1b. The prices are now at the top, in constants. In the calc_discount function there are consecutive if and return statements instead of elif: when return runs, the function ends immediately, so the second if is reached only if the first condition is false. The main code is three lines and reads like an English sentence: find the subtotal, find the discount, print the receipt.
Look at the parameter names of calc_subtotal: latte, cookie, tea. They are local; even if the main code had global variables with the same names, they would not be mixed up. print_receipt, on the other hand, returns nothing, it only prints; that is why we did not assign its result to a variable in the main code. As you saw in lesson 14, a function without a return returns None.
Below, we added a latte_count variable to the first line of the main code. Change its value and each time look at which return line in the calc_discount function runs: the highlighted lines are the lines that ran.
Change the latte count: which discount tier runs?
Pick a value; predict the output first, then look.
1LATTE = 4.252COOKIE = 2.003TEA = 1.2545def calc_subtotal(latte, cookie, tea):6 return latte * LATTE + cookie * COOKIE + tea * TEA78def calc_discount(amount):9 if amount >= 15:10 return amount * 15 / 10011 if amount >= 10:12 return amount * 10 / 10013 return 01415def print_receipt(subtotal, discount):16 print(f"Subtotal: ${subtotal:.2f}")17 print(f"Discount: ${discount:.2f}")18 print(f"Total due: ${subtotal - discount:.2f}")1920latte_count = 221subtotal = calc_subtotal(latte_count, 1, 2)22discount = calc_discount(subtotal)23print_receipt(subtotal, discount)
Subtotal: $13.00 Discount: $1.30 Total due: $11.70
Faded lines didn't run with this value. With 0 lattes the subtotal is $4.50: both conditions are false, and the return 0 at the bottom runs. With 2 lattes the subtotal is $13.00: the second return (10 percent) runs. With 3 lattes the subtotal is $17.25: the first return (15 percent) runs and the function ends there. The rest of the receipt did not change at all; the rule lives only inside calc_discount.
The order of the lines in the main code matters too, because each line uses the value produced by the previous one. Arrange the lines below in the order that will print the receipt's total due.
Put the lines of the main code in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You may think, "We wrote more lines for the same output." True, the number of lines went up a little; but there are three big gains.
A rule changes in one place. Say the café runs a promotion and the $10 threshold becomes $7.50. In Example 1b you know where to look: the calc_discount function. You do not need to read the rest of the receipt. If a price changes, you change a single constant.
Each part can be tested on its own. By writing print(calc_discount(20)), you can test the discount rule independently of the rest of the receipt: you expect 3.0, does 3.0 come out? Is calc_discount(9.99) 0? Is calc_discount(10) 1.0? When a problem appears, you find which part it is in by trying them one by one. In lesson 19 you will turn these tries into automatic tests.
Easy-to-understand functions. calc_subtotal and calc_discount look only at their parameters and the constants, change nothing outside, and always give the same result for the same input. To understand such a function, reading only its own lines is enough. To understand a function that changes a global value from inside, you have to read the whole program.
The same method also works outside the café. Think of a teacher's grade calculation: the midterm is weighted 40 percent and the final 60 percent; a letter grade is given based on the average, and a single line is written to the report card. Three jobs, three functions.
Example 4 (outside the case): A report card line
def average(midterm, final): return midterm * 0.4 + final * 0.6 def letter_grade(avg): if avg >= 85: return "A" if avg >= 70: return "B" if avg >= 50: return "C" return "F" def report_line(name, midterm, final): avg = average(midterm, final) return f"{name}: {avg:.1f} {letter_grade(avg)}" print(report_line("Ada", 60, 80)) print(report_line("Noah", 90, 85)) print(report_line("Maya", 40, 45))
OutputAda: 72.0 B
Noah: 87.0 A
Maya: 43.0 Freport_line calls the other two functions and returns the result as a string. Short names like avg can be used comfortably inside each function, because the avg of report_line and the avg parameter of letter_grade are two separate local variables. If the letter grade boundaries change, you touch only letter_grade.
Now it is your turn. Example 1b is ready below. Try three things in order: (1) Promotion: the $10 threshold became $7.50. Update the rule by changing only one line. (2) Add print(calc_discount(7.5), calc_discount(20)) below the main code and test calc_discount on its own. (3) Below the last line of print_receipt, add an undefined name like print(tax_amount), run it, read the message with two File lines, and undo the line.
Try it now· not graded; doesn't affect progress
When you start decomposing, writing only the names and parameters of the functions and putting pass in the body turns the plan into code. The program runs; functions that are not written yet return None.
# 1. Find the subtotal def calc_subtotal(latte, cookie, tea): pass # 2. Find the discount def calc_discount(amount): pass print(calc_subtotal(2, 1, 2)) print(calc_discount(13))
OutputNone
NoneThen you write the body of calc_subtotal and fix it until the first line prints 13.0; after that you move on to calc_discount. At each step you deal with only one part.
A parking lot charges $1.50 per hour, with a daily maximum of $10. Finding the duration, finding the fee, and printing the ticket are three separate jobs.
HOURLY_RATE = 1.50 DAILY_CAP = 10 def calc_hours(start, end): return end - start def calc_fee(hours): amount = hours * HOURLY_RATE if amount > DAILY_CAP: return DAILY_CAP return amount def print_ticket(plate, hours, amount): (f) hours = calc_hours(9, 12) print_ticket(, hours, calc_fee(hours)) hours = calc_hours(8, 18) print_ticket(, hours, calc_fee(hours))
Using `print` instead of `return` in a function that calculates. When splitting a program, if you print the result inside the function and forget to return it, the line waiting for the result gets None:
def calc_discount(amount): if amount >= 10: print(amount * 10 / 100) subtotal = 12.50 discount = calc_discount(subtotal) print(subtotal - discount)
On the screen:
Output1.25
Traceback (most recent call last):
File "<code>", line 7, in <module>
print(subtotal - discount)
~~~~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'1.25 appeared on the screen but did not go to discount; discount became None, and you cannot subtract None from a number. The right way: the function that calculates returns with return amount * 10 / 100, and it also returns a value in every case (return 0); the printing job lives in a separate function like print_receipt.
return.register += amount raises UnboundLocalError. The right way is register = make_sale(register, amount): take a parameter, return the new value.Next lesson: The program is split into parts; in the next lesson we will read how the traceback shows the "who called whom" chain when one part crashes.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputA-12 | 3 hours | $4.50
B-07 | 10 hours | $10.00The amount inside calc_fee is local; it has the same name as the amount parameter of print_ticket, but they are two separate boxes. If the cap changes, only the DAILY_CAP constant changes.