← Back to course
Code Crew G4 / Week 10 / Friday
5/6
Week 10 Β· Functions that return

Friday

Debug a function
// Name it, feed it, get an answer
⏱ about 15 min

Friday: Debug a function

Rocket writes a function that adds up a whole list of trips. When he calls it, the right total appears. But the next line says Week total: None.

"None? What is None?" he asks. Raven reads the function slowly. "What do you notice about the last line inside it? It shows the total, but does it hand it back?"

Nova highlights the word print in amber. "Let's debug together. Would you like a hint? A function without return hands back nothing at all."

The missing return

This function shows the total, but it never returns it.

def total_fuel(trips):
    total = 0
    for t in trips:
        total = total + t
    print(total)

week = total_fuel([12, 8, 15])
print("Week total:", week)
The screen shows
35
Week total: None

None is Python's word for no value. A function with no return gives back None.

The fix: change print(total) to return total. Then week holds 35.

def total_fuel(trips):
    total = 0
    for t in trips:
        total = total + t
    return total

week = total_fuel([12, 8, 15])
print("Week total:", week)
The screen shows
Week total: 35
SPOT THE BUG
  • Read the question.
  • Tap your answer.
Why did the first version show None?

Functions using functions

def total_fuel(trips):
    total = 0
    for t in trips:
        total = total + t
    return total

def can_fly(trips, budget):
    return total_fuel(trips) <= budget

print(can_fly([20, 30], 60))
print(can_fly([20, 30, 15], 60))
First line on the screen
Second line on the screen
Change to the fixed total_fuelWould Week total: 35 still show?
Rename t to trip on both lines?
Indent return total one more level?
Call it with [15, 8, 12]?
WHY THIS EXERCISEWhere a return sits matters. Inside the loop, it ends the function too early.
At the computer
This is never required.
If a grown-up has set up Python from python.org, type the buggy version into IDLE.
See None for yourself, then fix it.

Bug 2: the return that left early

def count_big(nums):
    count = 0
    for n in nums:
        if n > 10:
            count = count + 1
        return count

print(count_big([12, 15, 3, 20]))
FIND THE BUG
  • Read the question.
  • Tap your answer.
What does the program show?
Why is the answer wrong?
How do you fix it?
Call to the fixed count_bigDoes it return 3?
count_big([12, 15, 3, 20])?
count_big([11, 12, 13])?
count_big([10, 10, 10])?
count_big([1, 50, 99, 2])?
WHY THIS EXERCISETesting with different lists, edge cases too, proves the fix works.
In the buggy version, what does count_big([2, 40, 50]) return?
WHY THIS EXERCISERound 1 sees only the 2, so count is still 0 when return runs.

Week ten is done! You can define, call, pass values and return answers. Next week, you will clean up a long program with functions.

← Thursday