A for loop goes through a collection of things one at a time and runs its block once for each. You name a variable that holds the current thing on each iteration. Here the collection is a string, and the variable letter holds one character each time round:
for letter in "cat":
print(letter)
Prints
c
a
t
To repeat something a set number of times, loop over range(). range(5) gives the numbers 0, 1, 2, 3, 4: it starts at 0 and stops just before 5, so you get exactly five numbers. range(1, 6) gives 1 to 5, and a third number is the step: range(0, 20, 5) gives 0, 5, 10, 15.
for i in range(3):
print("Hello", i)
for n in range(10, 0, -3):
print(n)
Prints
Hello 0
Hello 1
Hello 2
10
7
4
1
A negative step counts down. A for loop is usually tidier than while when you know how many times to go round, because you can't forget to change the counter.
The running-total pattern from the last lesson is shorter with for:
total = 0
for n in range(1, 101):
total += n
print(total)
Prints
5050
continue skips the rest of the block and moves on to the next item. break works here too.
for n in range(1, 8):
if n % 2 == 0:
continue
print(n)
Prints
1
3
5
7
A loop can sit inside another loop. The inner one runs all the way through for every single iteration of the outer one. That's how you go through the rows and columns of a grid.
for row in range(1, 4):
line = ""
for col in range(1, 4):
line += str(row * col) + " "
print(line)
Prints
1 2 3
2 4 6
3 6 9
Practice
What does this print? (Separate the lines with spaces.)
for i in range(4):
print(i)
More info
Quick reference
for x in things:
Runs the block once for each item, with x holding the current one.
range(stop)
0 up to stop - 1.
range(start, stop, step)
From start, stepping by step, stopping before stop. A negative step counts down.
continue
Skip to the next iteration.
nested loops
A loop inside a loop: the inner one runs fully for each outer iteration.