Every pilot asks the same two questions. How much fuel do my trips need? And does that fit the budget? Rocket has answered by hand all week.
"Let's build it once and use it forever," he says. Raven nods. "What do you notice? Each question is a small job. Each job could be a function."
Nova draws two glowing boxes, one feeding into the other. "Would you like a hint? Give each function one job, and return its answer."
def fuel_needed(trips, per_trip):
return trips * per_trip
def within_budget(need, budget):
return need <= budget
plan = fuel_needed(3, 12) + fuel_needed(2, 20)
print(plan)
print(within_budget(plan, 80))
print(within_budget(plan, 70)) | The screen shows |
|---|
| 76 |
| True |
| False |
fuel_needed(3, 12) returns 36. fuel_needed(2, 20) returns 40. Together they make 76.
within_budget returns a Boolean: True or False. A comparison can be returned like any value.
def fuel_needed(trips, per_trip):
return trips * per_trip
budget = 100
need = fuel_needed(5, 18)
if need <= budget:
print("Go, with", budget - need, "to spare")
else:
print("Over by", need - budget) def water_needed(crew, days):
return crew * days * 2
def enough(have, need):
return have >= need
need = water_needed(3, 4)
print(need)
print(enough(30, need))
print(enough(20, need)) | Statement | True or false? |
|---|---|
| A function can return True or False. | ? |
| water_needed must be rewritten for each trip. | ? |
| need holds the value water_needed returned. | ? |
| enough(10, 24) returns True. | ? |
Your fuel budget is built from functions now! Tomorrow you will debug a function that forgot to return.