Loops: for and while
How to make Python repeat work for you
for (repeat a set number of times, or once for each item) and while (repeat as long as something is true).
- write a
forloop withrange(), - loop over a list or a string,
- write a
whileloop and avoid endless loops, - use
breakto stop early andcontinueto skip a turn.
1. What is a loop?
Imagine you have to write "I will tidy my room" ten times. You could type the sentence ten times... or you could tell a friend: "repeat this sentence ten times." A loop is how you tell that to a computer.
Analogy: a loop is like the chorus of a song. You do not print the chorus lyrics again and again on the page — you just write "repeat chorus". The loop is Python's way of saying "do this part again."
2. The for loop with range()
The for loop repeats its body once for each value it is given. The helper range() gives Python a sequence of numbers to count through. Notice the colon : at the end of the line and the indentation (spaces) that shows which lines are inside the loop.
for i in range(5):
print(i)
Expected output:
0
1
2
3
4
range(5) counts from 0 up to but not including 5, so we get 0, 1, 2, 3, 4 — that is five numbers. You can also give range() a start and a stop:
for i in range(1, 4):
print(i)
Expected output:
1
2
3
And a third number sets the step (how much to jump each time):
for i in range(0, 10, 2):
print(i)
Expected output:
0
2
4
6
8