CIS 2020 · Python for Everyone · Module 11 · Study guide
In Module 10 you wrote functions that work out an answer and return it. This module finishes the picture. Some functions do a job instead of giving back an answer. Good functions come from spotting code you keep repeating. Every variable has a scope, the part of the program where its name works. The last section, which is optional, shows a function that calls itself. Every example prints its result, so run each one and check your prediction.
Section 5.5
Not every function answers a question. Some just do a job, such as printing a banner or drawing a row of stars. These functions send nothing back, and you call them on a line by themselves.
def print_banner(text):
line = "=" * (len(text) + 4)
print(line)
print("|", text, "|")
print(line)
print_banner("Hello")
print_banner("Module 11")
========= | Hello | ========= ============= | Module 11 | =============
The function still has a parameter, text, so each call can print a different banner. It just has nothing to hand back. Its whole job is the printing.
A function that returns a value is usually part of a bigger line: total = add(2, 3). A function without a return value is a complete statement by itself:
def print_row(symbol, width):
print(symbol * width)
for size in range(1, 5):
print_row("#", size)
# ## ### ####
NoneEvery Python function gives back something. If there is no return, it gives back None, Python's word for "nothing." So there is no point storing the result:
def print_banner(text):
line = "=" * (len(text) + 4)
print(line)
print("|", text, "|")
print(line)
result = print_banner("Hi")
print("result is", result)
====== | Hi | ====== result is None
The banner printed, because the function ran. But result holds None. You saw the same thing in Module 10 when a function forgot its return. The difference here is that it is on purpose.
def print_receipt_line(item, price, quantity):
total = price * quantity
print(f"{quantity} {item} at ${price:.2f} each: ${total:.2f}")
print_receipt_line("tacos", 3.50, 4)
print_receipt_line("drinks", 1.25, 2)
4 tacos at $3.50 each: $14.00 2 drinks at $1.25 each: $2.50
The function works out total, but only to print it. If another part of the program needed that total (for a grand total, say), the function should return it instead. See the f-strings guide if :.2f looks unfamiliar.
returnYou can write return with nothing after it. It ends the function right there and gives back None. This is handy for skipping bad input.
def print_stars(count):
if count <= 0:
print("Nothing to draw")
return
print("*" * count)
print_stars(5)
print_stars(0)
print_stars(3)
***** Nothing to draw ***
For 0, the bare return stops the function before it reaches the last line.
| The function should | Use | Example call |
|---|---|---|
| work out an answer the program will use later | return the answer | area = rectangle_area(3, 4) |
| show something to the user, and that is all | no return value | print_banner("Hello") |
Common mistake: printing inside the function and then printing the call too.
def say_hi(name):
print("Hi,", name)
print(say_hi("Ana"))
Hi, Ana None
The function prints the greeting, then the outer print prints what the function gave back, which is None. Write just say_hi("Ana").
Section 5.6
When you notice you have written almost the same lines twice, that is a function waiting to be written. The parts that change become parameters.
This program reads a time of day. It needs the hours to be 0 to 23 and the minutes to be 0 to 59, so it checks both:
hours = int(input("Enter hours (0 to 23): "))
while hours < 0 or hours > 23:
print("Please enter a number from 0 to 23")
hours = int(input("Enter hours (0 to 23): "))
minutes = int(input("Enter minutes (0 to 59): "))
while minutes < 0 or minutes > 59:
print("Please enter a number from 0 to 59")
minutes = int(input("Enter minutes (0 to 59): "))
The two blocks are the same four lines. Only three things are different: the prompt, the lowest allowed value, and the highest allowed value.
def read_int_between(prompt, low, high):
value = int(input(prompt))
while value < low or value > high:
print("Please enter a number from", low, "to", high)
value = int(input(prompt))
return value
hours = read_int_between("Enter hours (0 to 23): ", 0, 23)
minutes = read_int_between("Enter minutes (0 to 59): ", 0, 59)
print(f"The time is {hours}:{minutes:02d}")
Enter hours (0 to 23): 25 Please enter a number from 0 to 23 Enter hours (0 to 23): 9 Enter minutes (0 to 59): 5 The time is 9:05
Now the checking logic lives in one place. If you find a bug in it, you fix it once. If next week you need a month (1 to 12) or a test score (0 to 100), you already have the function: read_int_between("Month: ", 1, 12).
return it. If the job is only printing, no return value is needed (Section 5.5).read_int_between.Before, with the same loop written twice:
first = "banana"
count = 0
for letter in first:
if letter in "aeiou":
count = count + 1
print(first, "has", count, "vowels")
second = "rhythm"
count = 0
for letter in second:
if letter in "aeiou":
count = count + 1
print(second, "has", count, "vowels")
After, with the loop written once:
def count_vowels(text):
count = 0
for letter in text.lower():
if letter in "aeiou":
count = count + 1
return count
print("banana has", count_vowels("banana"), "vowels")
print("rhythm has", count_vowels("rhythm"), "vowels")
print("Education has", count_vowels("Education"), "vowels")
banana has 3 vowels rhythm has 0 vowels Education has 5 vowels
Notice the bonus: adding .lower() in one spot fixed capital letters for every call. In the copied version you would have had to remember to fix each copy.
Why return here instead of print? count_vowels returns the count, so the caller can print it, compare it, or add it up. A function that returns a value is easier to reuse than one that prints, because the caller decides what to do with the answer.
For more ways to check what a user types, see the input validation examples.
Section 5.8
The scope of a variable is the part of the program where you can use its name. A variable made inside a function only exists inside that function.
def make_greeting(name):
message = "Hello, " + name
return message
print(make_greeting("Ana"))
print(message)
Hello, Ana NameError: name 'message' is not defined
message is a local variable: it was created inside make_greeting, and it vanished when the function returned. The function's parameter, name, is local too. If the caller needs the value, the function has to return it, which this one does. Store the call in a variable: greeting = make_greeting("Ana").
def first():
count = 1
print("first sees", count)
def second():
count = 99
print("second sees", count)
first()
second()
first()
first sees 1 second sees 99 first sees 1
Setting count to 99 in second did not touch the count in first. This is good news: when you write a function, you never have to worry that your variable names clash with names in some other function.
A variable created outside every function, at the left margin, is a global variable. Any function can read it.
TAX_RATE = 0.08
def price_with_tax(price):
return round(price * (1 + TAX_RATE), 2)
print(price_with_tax(100))
print(price_with_tax(19.99))
108.0 21.59
Writing the name in capital letters is a convention that says "this is a constant, nobody changes it." Reading a global constant like this is fine.
score = 10
def reset():
score = 0
print("inside:", score)
reset()
print("outside:", score)
inside: 0 outside: 10
The line score = 0 inside the function does not change the global. It creates a brand new local variable that happens to have the same name, which shadows (hides) the global one inside the function. The global score is still 10.
counter = 0
def add_one():
counter = counter + 1
add_one()
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
Because the function assigns to counter, Python treats counter as local everywhere in that function. So on the right side of the =, it looks for a local counter that does not have a value yet.
def add_one(value):
return value + 1
counter = 0
counter = add_one(counter)
counter = add_one(counter)
print(counter)
2
Python does have a global keyword (global counter as the first line of the function) that lets a function change a global variable. It works, but avoid it. When any function can change a value, a bug could come from anywhere in the program. Parameters and return values keep each function's inputs and outputs in plain sight.
if blocks do not make a new scopeOnly functions create a new scope. A variable made inside a loop is still there after the loop ends:
for i in range(3):
last = i * 10
print("i is", i)
print("last is", last)
i is 2 last is 20
| Created | Kind | Can be used |
|---|---|---|
| at the left margin, outside every function | global | anywhere after it is created, and read inside any function |
| inside a function, including its parameters | local | only inside that function, only while it runs |
inside a loop or if block | same as the code around it | after the block too, in the same function or program |
The rule of thumb: a function should get what it needs through its parameters and give back what it produces with return. Global constants in capital letters are the one common exception.
Section 5.10 Optional
A recursive function is a function that calls itself. Each call works on a smaller version of the same problem, until the problem is so small the answer is obvious.
def countdown(n):
if n == 0:
print("Liftoff!")
else:
print(n)
countdown(n - 1)
countdown(3)
3 2 1 Liftoff!
Every recursive function has two parts:
n == 0.n and calls countdown(n - 1), so each call is one step closer to 0.| Call | Base case? | What it does |
|---|---|---|
| countdown(3) | no | prints 3, then calls countdown(2) |
| countdown(2) | no | prints 2, then calls countdown(1) |
| countdown(1) | no | prints 1, then calls countdown(0) |
| countdown(0) | yes | prints Liftoff! and stops calling |
The factorial of 5, written 5!, is 5 × 4 × 3 × 2 × 1 = 120. Notice that 5! is just 5 × 4!, and 4! is 4 × 3!, and so on down to 1! = 1. That is a recursive definition, and it turns straight into code:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(1))
print(factorial(3))
print(factorial(5))
1 6 120
Here is how factorial(3) works it out. Each call waits for the one below it, then the answers come back up:
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * 1)
= 6
Where you put the print matters. This function draws a triangle of squares. It calls itself first, so the smaller rows print before the bigger ones:
def print_triangle(side):
if side < 1:
return
print_triangle(side - 1)
print("[]" * side)
print_triangle(4)
[] [][] [][][] [][][][]
To draw a triangle of side 4, draw a triangle of side 3, then add a row of 4. The base case uses the bare return from Section 5.5: a triangle smaller than 1 has nothing to draw.
def digit_sum(n):
if n < 10:
return n
else:
return n % 10 + digit_sum(n // 10)
print(digit_sum(7))
print(digit_sum(1234))
7 10
n % 10 is the last digit and n // 10 is the number without its last digit. So the digit sum of 1234 is 4 plus the digit sum of 123, and so on until one digit is left.
Common mistake: no base case, or a recursive call that never gets closer to it.
def countdown(n):
print(n)
countdown(n - 1) # no base case: never stops
countdown(3)
3 2 1 0 -1 -2 (about a thousand more lines) RecursionError: maximum recursion depth exceeded
Python gives up after about a thousand calls deep. If you see RecursionError, check two things: is there a base case, and does every call move toward it?
Do you need recursion? Everything on this page could also be written with a loop, and for problems this small a loop is usually simpler. Recursion shines on problems that are naturally made of smaller copies of themselves, such as folders inside folders. It is optional for this course, but it is a classic idea worth seeing once.
None.return ends a function early without sending back a value.print(), or you will also see None.return, instead of changing globals.