for walks a sequence. while repeats until a condition is false. range makes integer sequences.
Goal
Loop with for, range, enumerate, zip, and break/continue.
for
for city in ["Nairobi", "Mombasa", "Kisumu"]:
print(city)range
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 10, 2)))
for n in range(1, 4):
print(n, n ** 2)range is not a list until you ask (list(range(...))). It is fine to loop it directly.
enumerate and zip
names = ["Ada", "Alan", "Grace"]
scores = [98, 91, 95]
for i, name in enumerate(names, start=1):
print(i, name)
print()
for name, score in zip(names, scores):
print(f"{name}: {score}")while
n = 3
while n > 0:
print(n)
n -= 1
print("done")break and continue
for n in range(8):
if n == 0:
continue
if n == 5:
break
print(n)continue skips the rest of this round. break leaves the loop.
Accumulate
total = 0
for score in [98, 91, 95, 88]:
total += score
print(total, total / 4)Pitfall
while True: without break never finishes. If a cell hangs, stop and edit the condition.