Imagine being asked to write "I will not shout in class" a hundred times. You would want a way to say "do this a hundred times." That is what a loop does: it repeats instructions so you don't have to write them again and again.
The for loop: repeat a set number of times
for i in range(3):
print("Hello!")This prints "Hello!" three times. Here is how to read it:
forstarts the loop.range(3)means "three times."- The colon
:ends the line. - The indented line is the part that repeats. Those spaces matter.
The i is a variable that counts as the loop goes round. Try printing it:
for i in range(3):
print("Round", i)It prints Round 0, Round 1, Round 2. Notice Python starts counting at 0, not 1. That surprises everyone at first.
Looping over a list
A for loop is also great for going through a list:
pets = ["cat", "dog", "fish"]
for pet in pets:
print("I have a", pet)Each time round, pet becomes the next item in the list.
The while loop: repeat until something changes
A while loop keeps going as long as a condition is true.
count = 3
while count > 0:
print(count)
count = count - 1
print("Lift off!")This counts down from 3 and finishes with "Lift off!". Each time round, count gets smaller. When it reaches 0 the condition count > 0 is no longer true, so the loop stops.
Beware the endless loop
If nothing inside a while loop ever makes the condition false, it runs forever:
count = 3
while count > 0:
print(count)Here count never changes. If this happens, stop the program with the stop button, or press Ctrl+C in a terminal. It happens to every programmer, and it's a good bug to hunt together.
Which loop should I use?
- Use for when you know how many times, or you're going through a list.
- Use while when you want to repeat until something happens, such as until a player types "quit."
Common mistakes
- Forgetting the colon at the end of the
fororwhileline. - Forgetting to indent the lines that should repeat.
- Expecting
range(5)to include 5. It gives 0, 1, 2, 3, 4.
Challenges to try
- Print your name five times.
- Print the numbers 1 to 10. (Hint:
range(1, 11).) - Print the 3 times table up to 12.
- Make a countdown from 10 that ends with "Blast off!".
For more practice, try the For Loops lesson in the Python course, and read about Python if statements next.