Rocket's morning report program has grown to ninety lines. The same three banner lines appear in five different places, and today he needs to change the banner title.
"Five places," he groans. "I will miss one. I always miss one."
Raven scrolls through the program and marks each copy with her finger. "What do you notice?" she asks. "It is the same job every time. Draw the banner."
Nova projects a small labeled box around the three lines. "Would you like a hint?" she asks. "Give that job a name. Write it once. Then call it by name wherever you need it."
Rocket types def banner(): and feels the program getting lighter.
def starts a function definition. Then comes the name, a pair of round brackets, and a colon. The indented lines below are the function body.
Defining a function does not run it. The body runs only when you call the function by writing its name with brackets, like banner().
# banner_fn.py
def banner():
print("*" * 20)
print(" MISSION CONTROL")
print("*" * 20)
banner()
print("Morning briefing")
banner() ******************** MISSION CONTROL ******************** Morning briefing ******************** MISSION CONTROL ********************
Python reads from the top. If you call a function on a line above its def, Python has not met it yet, and you get a NameError.
# too_early.py
banner()
def banner():
print("*" * 20) Traceback (most recent call last):
File "too_early.py", line 2, in <module>
banner()
^^^^^^
NameError: name 'banner' is not defined A function body can call another function. Big jobs are often built from small ones this way, like a report that uses a divider line.
When a call finishes, Python goes back to the line just after the call and carries on.
# report_fn.py
def line():
print("-" * 16)
def report():
line()
print("Fuel: OK")
print("Crew: OK")
line()
report()
print("Next shift")
report() | Statement | True or false? |
|---|---|
| A function can call another function. | ? |
| Defining a function runs its body straight away. | ? |
| After a function finishes, Python goes back to the line after the call. | ? |
| A function must be called exactly once. | ? |
A function turns a repeated job into one clear name. Tomorrow you will pass values into functions.