Quarry School

Functions: crash course

about 6 min to listen5 lessons0 questions to tryUnit 6 of 6

Short view. Each lesson's rule, its steps and its trap. Switch to Full for a worked example and a question to try in every lesson.Full view. Each lesson's rule, its steps, one worked example with Watch it solved, the trap, and one question to try.

Starts here no skill from another unit needed first

1 Give a repeated task a name

about 1 minOpen the full lessonOnly this lesson

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.

How

  1. Find the lines that the program needs in more than one place.
  2. Write def, a name that says what the lines do, an empty pair of parentheses and a colon.
  3. Put the lines under the def line and indent them one more level, four spaces, keeping any deeper indentation they already have.
  4. Leave the indented block, and write the function's name with parentheses at each place where the lines should run.
  5. Trace the program: skip the body at the def line, and run the body at each call.

Worked example

Call one function twice

Python code
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

Python code
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.

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.

2 Pass an argument

about 1 minOpen the full lessonOnly this lesson

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.

How

  1. Find the value in the body that should change from call to call.
  2. Give that value a name and write the name inside the parentheses of the def line. For two values, write two names with a comma between them.
  3. Use the names in the body where the values were.
  4. In each call, write the values inside the parentheses in the same order as the names.
  5. Trace a call by writing each parameter with the argument it received, then running the body with those values.

Worked example

Greet two guests with one function

Python code
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

Python code
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

Python code
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.

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.

3 Return a result

about 1 minOpen the full lessonOnly this lesson

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.

How

  1. Decide what value the rest of the program needs from the function.
  2. Write return followed 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.
  3. At the call, do something with the value: give it a name, print it or use it in an expression.
  4. Trace a call by replacing it with the value it returns, then finishing the line the call was in.
  5. If a function should only display something, leave return out and call it on a line of its own.

Worked example

Use a returned price twice

Python code
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

Python code
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

Python code
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.

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.

4 Trace a local name

about 2 minOpen the full lessonOnly this lesson

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.

How

  1. Draw two columns for names: one for the file's global names and one for the call's local names.
  2. At a call, start a fresh local column and write each parameter in it with the argument it received.
  3. 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.
  4. 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.
  5. At a return line, work out the value to give back while the local column is still there.
  6. 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.

Worked example

Assign a name that also exists outside

Python code
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

Python code
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

Python code
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.

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.

5 Compose two small functions

about 1 minOpen the full lessonOnly this lesson

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.

How

  1. Write the task as a list of small jobs, each one taking some values and giving one value back.
  2. Write one function for each job, with a parameter for each value it takes. Return its result.
  3. Test each function that calls no other function alone, with a few arguments, including any boundary value. Compare with results worked out by hand.
  4. 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.
  5. 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.

Worked example

Join three functions into a receipt

Python code
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

Python code
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.

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.