Loop over a list
A list and a loop work well together. One way is for i in range(len(rain)): the counter i is each index, and rain[i] is the item. Use this when you also need the position. The other way is for amount in rain:. Here the variable amount holds each item in turn, from the first to the last, and no index is needed. Use this when only the values matter. Inside the loop you can use the usual patterns. A running total is set to 0 before the loop. A counter adds 1 when an IF finds a matching item. A best-so-far variable starts with the first item and is replaced when a better one comes. The IF is nested inside the for, so its lines are indented twice.
1rain = [0, 12, 5, 0, 20, 7] 2total = 0 3for amount in rain: 4 total = total + amount 5print("Total:", total)
Total: 44
1rain = [0, 12, 5, 0, 20, 7] 2for i in range(len(rain)): 3 print("Day", i + 1, rain[i])
Day 1 0 Day 2 12 Day 3 5 Day 4 0 Day 5 20 Day 6 7
1rain = [0, 12, 5, 0, 20, 7] 2dry = 0 3biggest = rain[0] 4for amount in rain: 5 if amount == 0: 6 dry = dry + 1 7 if amount > biggest: 8 biggest = amount 9print("Dry days:", dry) 10print("Wettest:", biggest)
Dry days: 2 Wettest: 20
| amount | dry | biggest |
|---|---|---|
| (before) | 0 | 0 |
| 0 | 1 | 0 |
| 12 | 1 | 12 |
| 5 | 1 | 12 |
| 0 | 2 | 12 |
| 20 | 2 | 20 |
| 7 | 2 | 20 |
Row of cards (no computer). Write six numbers between 0 and 30 on cards and lay them in a row, face up. Make a trace table with the columns item, total and biggest. Move a finger along the row. At each card, update the total and compare with the biggest so far. Then turn all the cards face down, put one random card up at a time, and decide how you would find the smallest by comparing with the smallest so far. Finally, count how many cards are greater than 10.
1temps = [21, 24, 19, 23] 2total = 0 3for t in temps: 4 total = total + t 5print(total / len(temps))
1sizes = [8, 3, 9, 1, 6] 2smallest = sizes[0] 3for s in sizes: 4 if s < smallest: 5 smallest = s 6print(smallest)
1answers = ["Yes", "no", "YES", "yes", "No"] 2count = 0 3for a in answers: 4 if a.lower() == "yes": 5 count = count + 1 6print(count)