Lecture 3
A for loop runs the same lines once for every item.
The indented lines run once for each item, with the loop variable set to that item. Two patterns come up again and again: a running total that starts at 0, and a new list that starts empty.
total = 0doubled = []for v in [2, 3, 5]: total += v doubled.append(v * 2)print(total, doubled)Output
10 [4, 6, 10]
range(stop) counts from 0 up to — not including — stop. range(start, stop, step) changes where it starts and how far it jumps.
print(list(range(4)))print(list(range(2, 6)))print(list(range(0, 10, 3)))Output
[0, 1, 2, 3] [2, 3, 4, 5] [0, 3, 6, 9]
break leaves the loop straight away; the loop variable keeps its last value.
for v in [3, 8, 2, 9]: if v > 5: breakprint(v)Output
8
From the advanced notebook — this is what the advanced questions test.
enumerate() gives each position together with its item. zip() walks two lists side by side.
for i, b in enumerate("GAT"): print(i, b)for a, b in zip([1, 2], [10, 20]): print(a * b)Output
0 G 1 A 2 T 10 40
[expression for item in list] builds a new list in one line.
print([x * x for x in range(5)])Output
[0, 1, 4, 9, 16]
A while loop repeats as long as its condition is True — use it when you do not know in advance how many runs you need.
n = 1steps = 0while n < 100: n = n * 3 steps += 1print(n, steps)Output
243 5