Page 1
for loops
A for loop repeats a block once for each item in a sequence or other collection, such as a list, a string, a range, a tuple, a dictionary or a set. The loop variable takes each item in turn.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherryLooping over a string gives one character at a time:
for ch in "hi":
print(ch) # h, then iA for loop stops by itself when it runs out of items. Each pass through the loop body is called an iteration.
Page 2
range(start, stop, step)
The built-in range() makes a sequence of whole numbers, which is perfect for counting loops.
- range(stop) counts from 0 up to, but not including, stop: range(5) gives 0, 1, 2, 3, 4.
- range(start, stop) starts at start: range(2, 6) gives 2, 3, 4, 5.
- range(start, stop, step) moves by step each time: range(0, 10, 3) gives 0, 3, 6, 9.
- A negative step counts down: range(5, 0, -1) gives 5, 4, 3, 2, 1.
The stop value is never included. range(5) has 5 numbers, but the last one is 4. The step can't be 0: range(1, 5, 0) raises a ValueError.
total = 0
for n in range(1, 4):
total += n
print(total) # 6 (1 + 2 + 3)Page 3
while loops
A while loop repeats its block as long as its condition is true. Python checks the condition before every iteration, so if it is false at the start, the body never runs.
count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")
# 3, 2, 1, Liftoff!Use while when you don't know in advance how many times to loop, such as asking for input until it is valid. Use for when you're stepping through a sequence or a known range.
If nothing in the body ever makes the condition false, you get an infinite loop: the program runs forever. Press Ctrl+C to stop it.
Page 4
break, continue and else
- break exits the loop immediately; the code after the loop runs next.
- continue skips the rest of the current iteration and jumps to the next one.
for n in range(10):
if n == 5:
break
if n % 2 == 0:
continue
print(n) # 1, then 3Loops can have an else block too. It runs when the loop finishes normally, and it is skipped if the loop ends with break. It is handy for searches:
for n in [3, 7, 9]:
if n % 2 == 0:
print("found an even number")
break
else:
print("no even numbers") # runs: no break happenedPage 5
Off-by-one errors
An off-by-one error is a loop that runs one time too many or one time too few. The most common cause is forgetting that range() stops before its stop value. To count from 1 to 10 inclusive, write range(1, 11), not range(1, 10).
Another cause is a while condition that uses < where you needed <=, or the other way round. Before you run a loop, check its first and last values by hand.
Finished reading?
Mark it as read for +20 XP. Optional: practice is open either way.