The supply team needs to know how much fuel the engines burn during a five-minute test. The engines burn 15 units every minute, starting from a full tank of 100.
Rocket grabs a calculator. "Five subtractions," he says. "Easy. But they want a report for every single minute, and they want it every day."
Raven sketches a small table with a row for each minute. "What do you notice?" she asks. "Each row starts from the row before it. The tank keeps going down from where it was."
Nova taps one cell of the table. "Would you like a hint?" she asks. "Make a variable before the loop. Inside the loop, change it a little each time round."
Rocket puts the calculator away and opens IDLE.
A variable made before a loop keeps its value from one round to the next. Each time round, the loop can change it a little. This is how loops build up totals or count things down.
# burn_test.py
fuel = 100
for minute in range(1, 6):
fuel = fuel - 15
print(f"Minute {minute}: fuel {fuel}")
print("Test over") Minute 1: fuel 85 Minute 2: fuel 70 Minute 3: fuel 55 Minute 4: fuel 40 Minute 5: fuel 25 Test over
An accumulator starts at 0 before the loop and adds to itself inside the loop. After the loop it holds the total.
# total.py
total = 0
for day in range(1, 8):
total = total + day
print("Total:", total) A for loop can also go through a string one character at a time. This program counts the letter o:
# count_o.py
message = "Mission Control"
count = 0
for letter in message:
if letter == "o":
count = count + 1
print("Letter o appears", count, "times") # even_count.py: counts and adds the even numbers from 1 to 10
count = 0
total = 0
for n in range(1, 11):
if n % 2 == 0:
count = count + 1
total = total + n
print("Even numbers:", count)
print("Their total:", total) | Statement | True or false? |
|---|---|
| A counter adds 1 each time something happens. | ? |
| An accumulator must start at 1. | ? |
| An if inside a loop is checked once for every round. | ? |
| print inside the loop would show the total only once. | ? |
Running totals and counters power most real programs. Tomorrow you will meet a loop that keeps going as long as a condition stays True.