Five temperature sensors send readings to Mission Control every hour. The weather team wants the highest, the lowest and the average, and they want them right now.
Rocket starts writing reading1, reading2, then stops himself. "No more numbered variables," he says. "These go in a list."
Raven nods at the screen. "What do you notice?" she asks. "We used for with range. Could for go through the list itself?"
Nova hums a short tune, one note per reading. "Interesting," she says. "A for loop can visit each item of a list in turn. And Python has tools that already know how to find the biggest and smallest."
Rocket types for t in temps and waits to see what happens.
for t in temps: runs the block once for each item. Each time round, t holds the next item. You choose the name; t is short for temperature.
Python also has built-in tools for lists of numbers: max() gives the biggest, min() the smallest, and sum() adds them all.
# readings.py
temps = [21, 19, 24, 22, 18]
for t in temps:
print("Reading:", t)
print("Highest:", max(temps))
print("Lowest:", min(temps))
average = sum(temps) / len(temps)
print(f"Average: {average:.1f}") Reading: 21 Reading: 19 Reading: 24 Reading: 22 Reading: 18 Highest: 24 Lowest: 18 Average: 20.8
enumerate() gives you a counter along with each item. With start=1 the counter begins at 1, which is how people like to number things.
# checklist.py
checklist = ["Fuel", "Weather", "Crew", "Doors"]
for number, item in enumerate(checklist, start=1):
print(f"{number}. {item}") 1. Fuel 2. Weather 3. Crew 4. Doors
# pack.py
items = []
while True:
item = input("Add an item (press Enter to finish): ").strip()
if item == "":
break
items.append(item)
print(f"You packed {len(items)} items.")
for item in items:
print("*", item) Add an item (press Enter to finish): compass Add an item (press Enter to finish): water Add an item (press Enter to finish): You packed 2 items. * compass * water
# warm_days.py: keeps only the readings above 20
temps = [21, 19, 24, 22, 18]
warm = []
for t in temps:
if t > 20:
warm.append(t)
print("Warm readings:", warm)
print("How many:", len(warm)) | Statement | True or false? |
|---|---|
| for t in temps gives t each reading in turn. | ? |
| min([4, 9, 2]) gives 9. | ? |
| sum([1, 2, 3]) gives 6. | ? |
| enumerate(items, start=1) numbers items starting at 0. | ? |
Loops and lists work beautifully together. Tomorrow you will meet dictionaries, which look things up by name instead of by position.