The station has 150 units of fuel for this week. Four trips are planned, and each one needs a different amount. Rocket wants to know two things: do the trips fit the budget, and which trip is the hungriest?
"I will add them on my tablet," he says. Raven shakes her head. "What do you notice? We already know how to total a list and find a champion."
Nova glows. "Would you like a hint? Put the patterns together. They work on records too."
trips = [
{"name": "Moon hop", "fuel": 30},
{"name": "Mars run", "fuel": 70},
{"name": "Ring tour", "fuel": 25},
{"name": "Comet chase", "fuel": 40},
]
budget = 150
total = 0
hungriest = trips[0]
for t in trips:
total = total + t["fuel"]
if t["fuel"] > hungriest["fuel"]:
hungriest = t
print("Total:", total)
print("Hungriest:", hungriest["name"])
if total <= budget:
print("Within budget")
else:
print("Over by", total - budget) | The screen shows |
|---|
| Total: 165 |
| Hungriest: Mars run |
| Over by 15 |
The champion here is a whole record, not just a number. That way the program can show its name.
The trips need 165 units, but the budget is 150. So the plan is 15 units over.
trips = [
{"name": "Probe", "fuel": 20},
{"name": "Lander", "fuel": 45},
{"name": "Scout", "fuel": 15},
]
budget = 90
total = 0
for t in trips:
total = total + t["fuel"]
left = budget - total
print("Total:", total)
print("Left:", left) | Statement | True or false? |
|---|---|
| total starts at 0 before the loop. | ? |
| left is worked out inside the loop. | ? |
| t["fuel"] is a number, so it can be added. | ? |
| Adding a fourth trip needs a new loop. | ? |
Week eight is done, Crew Engineer! You can store records and choose containers. Next week, your programs will ask the user questions.