GoalDefine a function with def and return, call it, and replace a call by its returned value when tracing.
New words
sub-routine · a named block of code that does one job and can be used again and againcall · to run a sub-routine by using its namefunction · a sub-routine that gives a value back to the place where it was calledreturn value · the value a function sends back
Explanation
A long program is easier to build when it is split into sub-routines. A sub-routine is a named block of code with one job. You write it once, and then call it whenever you need it by using its name. A function is a kind of sub-routine that hands a value back to the code that called it. In Python it starts with def, then the name, brackets and a colon. The indented lines are the body, and return sends the value back. The call is then replaced by that value. So total = 20 + get_fee() becomes total = 20 + 5. A function must be defined before the line that calls it runs. Calling a function does not print anything unless you print the value. In a flowchart, a call is a box with double side lines. Here it is drawn as an ordinary box that says call sub-routine.
Return does not print. The first call in the program gives back 5, but nothing is done with it, so nothing is shown. The second call is inside print, so the value is shown. The output has only one line.
Class activity
Call it out (no computer). Write the name of a small job on a card, such as get_fee, and write the value it returns on the back: 5. Make three more cards, for example lunch_cost with 7, bonus with 10 and ticket with 4. Your partner reads out a line such as 3 * lunch_cost(). You find the card, read the value on the back, and write the line again with the call replaced by the value. Then work out the answer. Do six calls, then swap. If you have a computer or tablet, type one function and a call and run it.
Practice
1
Trace the program. Replace the call by its returned value and say what is printed.
Two lines appear: Start, and then 12. The call bonus() on its own returns 10 but nothing is printed. The last line replaces bonus() with 10, adds 2 and prints 12.
3
Write a function pocket() that returns 15, then a line that stores pocket() * 2 in cost, and a line that prints cost. What is printed?
Model answer (lines are separated by /, and [indent] means four spaces at the start of the line): def pocket(): / [indent] return 15 / cost = pocket() * 2 / print(cost). Note: The call becomes 15, so cost is 30 and 30 is printed.
4
This program stops with an error. Say what the error is and explain what is wrong with the order of the lines.
Python
1print(ticket())
23def ticket():
4return4
It is a NameError, a runtime error. The call on line 1 runs before the function has been defined, so Python does not know the name ticket yet. Put the def lines first.