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."
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 |
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)) | Change to the fixed total_fuel | Would Week total: 35 still show? |
|---|---|
| Rename t to trip on both lines | ? |
| Indent return total one more level | ? |
| Call it with [15, 8, 12] | ? |
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])) | Call to the fixed count_big | Does 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]) | ? |
Week ten is done! You can define, call, pass values and return answers. Next week, you will clean up a long program with functions.