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

Thursday

The fuel budget function
// Name it, feed it, get an answer
⏱ about 15 min

Thursday: The fuel budget function

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

Two small functions

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.

What does fuel_needed(4, 15) return?
What does within_budget(60, 60) return?
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)
What number shows on the screen?
WHY THIS EXERCISEA function's answer can feed an if, just like any value.
REUSE IT
  • Read the question.
  • Tap your answer.
The rover needs 6 trips at 9 units each. Which call works it out?
Try it
Invent a function for your day, like steps_walked(blocks, steps_per_block).
Write what it would return for two calls.

Practice lab: the water 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))
What does line 8 show?
What does line 9 show?
What does line 10 show?
What does water_needed(2, 5) return?
BUDGET CHECK
  • Read the question.
  • Tap your answer.
What kind of value does enough return?
Which call works out water for 4 crew for 3 days?
What does enough(24, 24) return?
StatementTrue 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.?
WHY THIS EXERCISEWrite it once, call it with new arguments forever.
What does water_needed(1, 7) return?
WHY THIS EXERCISEOne crew member for 7 days needs 14 units.

Your fuel budget is built from functions now! Tomorrow you will debug a function that forgot to return.

← Wednesday