Lesson · 1 of 4
A loop is how a program does the same thing many times — once per item, or as long as a condition holds. They're the engine behind almost every piece of software: walking a list, polling a sensor, drawing every frame.
01 The for loop
Iterates over any sequence — a list, a string, a range, the keys of a dict, the lines of a file.
for i in range(3):
print(i)
# 0
# 1
# 2
Each iteration i is bound to the next item from the sequence. When the sequence runs out, the loop ends.
for ch in "hi":
print(ch)
# h
# i
for x in [10, 20, 30]:
print(x * 2)
# 20 40 60
02 range() — generating numbers
The most common companion to for. Three forms — each is half-open: start included, stop excluded.
range(stop)0, 1, … stop−1
range(start, stop)start, start+1, … stop−1
range(start, stop, step)arithmetic progression, step can be negative
list(range(5)) # [0, 1, 2, 3, 4]
list(range(2, 10, 3)) # [2, 5, 8]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]
03 enumerate & zip
Need the index along with the item? Reach for enumerate. Iterating two sequences in lockstep? zip.
for i, ch in enumerate("abc"):
print(i, ch)
# 0 a
# 1 b
# 2 c
names = ["a", "b"]
ages = [10, 20]
for n, a in zip(names, ages):
print(n, a)
04 The while loop
Repeats as long as a condition is true. Use it when you don't know in advance how many iterations you'll need.
x = 10
while x > 0:
x -= 3
print(x) # -2
Forget to make progress toward the exit condition and you've made an infinite loop — fine for servers, fatal for anything else. Always make sure something inside the body changes the condition.
05 break & continue
break leaves the nearest enclosing loop immediately. continue skips the rest of the current iteration and jumps back to the condition.
for n in range(10):
if n == 4:
break
print(n)
# 0 1 2 3
for n in range(5):
if n % 2 == 0:
continue
print(n)
# 1 3
06 The else on a loop
A surprising feature: else on a for or while runs only if the loop wasn't broken out of. Perfect for "didn't find it" logic.
for n in [2, 4, 7, 8]:
if n % 2:
print("odd:", n)
break
else:
print("all even")
# odd: 7
07 Nested loops
Loops inside loops. The inner loop runs fully for each step of the outer.
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()
# 1 2 3
# 2 4 6
# 3 6 9
08 Infinite cycles — itertools.cycle
For when you genuinely want a repeating, infinite stream of values. Pair it with islice to take only what you need.
from itertools import cycle, islice
list(islice(cycle("AB"), 5))
# ['A', 'B', 'A', 'B', 'A']