← Back to course
Code Crew G5 / Week 02 / Friday
5/6
Week 02 Β· Functions call functions

Friday

Helpers and a missing return
// Who waits, who returns
⏱ about 15 min

Friday: Helpers and a missing return

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."

Find the bug

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)
Which word fixes the blank, so report(3) prints Need: 15?
WHY THIS EXERCISEOnly return sends a value back. print only shows it on the screen.

Helpers make big jobs small

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
USE ENOUGH_FUEL FROM ABOVE.
  • Read the question.
  • Tap your answer.
What does enough_fuel(25, 5) return?
What does enough_fuel(10, 3) return?
At the computer
With a grown-up, type the buggy version into IDLE and run it.
Then fix it with return and run it again. Watch None turn into 15.

Bug 2: the answer that never left

def cells(hops):
    total = hops * 5

def report(hops):
    print("Cells:", cells(hops))

report(2)
FIND BUG 2
  • Read the question.
  • Tap your answer.
What does the program show?
Why does that happen?
Which line, added to the end of cells, fixes it?
FunctionDoes 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?
WHY THIS EXERCISEWithout return, every function hands back None.
After the fix, what number does report(4) show?
WHY THIS EXERCISEcells now returns 20, so report can print it.

Week 2 complete! You can trace calls, picture the stack and catch a missing return. Next week we meet a function that calls itself.

← Thursday