Before every probe trip, the fleet checks the fuel. Rocket builds a report with a helper function.
He runs it, and the screen says: Need: None.
"None? The probe needs fuel!" Rocket says. "My math must be wrong."
Raven reads the helper slowly. "What do you notice about how it gives back its answer?"
Nova shines a light on one line. "Here is a hint. Showing a value and handing it back are different jobs."
Each hop needs 5 fuel cells. Read Rocket's first try.
def fuel_needed(hops):
print(hops * 5)
def report(hops):
need = fuel_needed(hops)
print("Need:", need)
report(3) Output: 15 Need: None
fuel_needed prints 15 on the screen. But it never uses return. So the caller gets None back.
A bug like this is easy to make. Finding it is what debugging is for.
def fuel_needed(hops):
____ hops * 5
def report(hops):
need = fuel_needed(hops)
print("Need:", need)
report(3) Here the fixed helper is used inside a yes or no check. Splitting the job keeps each function short.
def fuel_needed(hops):
return hops * 5
def enough_fuel(tank, hops):
need = fuel_needed(hops)
return tank >= need
print(enough_fuel(40, 6))
print(enough_fuel(20, 6)) Output: True False
def cells(hops):
total = hops * 5
def report(hops):
print("Cells:", cells(hops))
report(2) | Function | Does it return a value that is not None? |
|---|---|
| def f(n): return n + 1 | ? |
| def f(n): print(n + 1) | ? |
| def f(n): x = n + 1 | ? |
| def f(n): return n > 1 | ? |
Week 2 complete! You can trace calls, picture the stack and catch a missing return. Next week we meet a function that calls itself.