CIS 2020 · Python for Everyone · Module 11 · Study guide

Module 11 review: functions without return values, reusable functions, scope, and recursion

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

Functions Without Return Values

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.

A function that does a job

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.

Call it on its own line

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)
#
##
###
####

What comes back is None

Every 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.

Several parameters, still no return

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.

Leave early with a bare return

You 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.

Which kind of function do you need?
The function shouldUseExample call
work out an answer the program will use laterreturn the answerarea = rectangle_area(3, 4)
show something to the user, and that is allno return valueprint_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

Problem Solving: Reusable Functions

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.

Spot the repeated code

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.

Turn the differences into parameters

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).

The recipe

  1. Find the copies. Look for blocks of code that are the same except for a few values.
  2. List what changes. Each value that is different between the copies becomes a parameter.
  3. Decide what comes out. If the caller needs a result, return it. If the job is only printing, no return value is needed (Section 5.5).
  4. Pick a clear name that says what the function does, such as read_int_between.
  5. Replace every copy with a call, then run the program again with the same tests to make sure nothing changed.

A second example: counting vowels

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

Variable Scope

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.

Global and local scope A large outer box labeled the whole program holds the global variable TAX_RATE. Inside it are two smaller boxes for the functions first and second. Each holds its own local variable named count, one with 1 and one with 99. The two count variables are separate. the whole program (global scope) TAX_RATE 0.08 every function can read this inside first() (local scope) count 1 gone when first() ends inside second() (local scope) count 99 a different count, same name
A global variable lives in the whole program. Each function call gets its own private space for its local variables, so two functions can use the same name without bumping into each other.

Local variables disappear when the function ends

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").

The same name in two functions is two different variables

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.

Global variables can be read anywhere

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.

Assigning inside a function makes a new local variable

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.

Reading and changing a global gives an error

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.

The fix: pass it in, return it out

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.

Loops and if blocks do not make a new scope

Only 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
Where a variable lives
CreatedKindCan be used
at the left margin, outside every functionglobalanywhere after it is created, and read inside any function
inside a function, including its parameterslocalonly inside that function, only while it runs
inside a loop or if blocksame as the code around itafter 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

Recursive Functions

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.

A countdown

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:

Trace it

What each call of countdown(3) does
CallBase case?What it does
countdown(3)noprints 3, then calls countdown(2)
countdown(2)noprints 2, then calls countdown(1)
countdown(1)noprints 1, then calls countdown(0)
countdown(0)yesprints Liftoff! and stops calling

A recursive function that returns a value

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

Work before or after the call

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.

One more: adding the digits of a number

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.

Quick check

If you remember only these

  • A function without a return value does a job, such as printing. Call it on its own line. It gives back None.
  • A bare return ends a function early without sending back a value.
  • Do not wrap a printing function in print(), or you will also see None.
  • When code repeats with small differences, write a function. The parts that change become parameters.
  • Returning a value makes a function easier to reuse than printing inside it.
  • Variables and parameters created inside a function are local. They disappear when the function ends.
  • Two functions can use the same variable name without affecting each other.
  • A function can read a global variable, but assigning to that name inside the function creates a new local variable.
  • Pass values in with parameters and send them out with return, instead of changing globals.
  • A recursive function calls itself. It needs a base case, and every call must move closer to that base case.