Functions — quick review
Give a repeated task a name
A recipe card titled Tea sits in a kitchen drawer.
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.
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.
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.
Pass an argument
A printed invitation leaves a blank after the word Dear.
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.
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.
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.
Return a result
A shop has a price board on the wall and a clerk with a calculator.
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.
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.
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.
Trace a local name
A workshop lends each visitor a tray of tools at the door.
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.
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.
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.
Compose two small functions
A stall at a market works out a bill in three small jobs.
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.
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.
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.