A for loop runs the same block of code once for every item in a collection: every name in a list, every letter in a word, every number in a range. It is how you stop copy-pasting the same line ten times.
THE BASIC SHAPE
Read it almost like English: for each snack in snacks, print the snack.
snacks = ["apple", "chips", "cookie"]
for snack in snacks:
print(snack)apple
chips
cookie
snackis the loop variable. Python gives it the next item on every pass. You can name it anything.- The line ends with a colon
:. - Everything indented under it (4 spaces) is the body that repeats.
COUNTING WITH RANGE()
To repeat something a number of times, loop over range(). It counts from 0 and stops before the number you give it.
for i in range(3):
print("Level", i)Level 0
Level 1
Level 2
You can also give a start, a stop and a step:
for n in range(2, 11, 2):
print(n)2
4
6
8
10
range(1, 5) gives 1, 2, 3, 4. The stop number is never included.LOOPING OVER A STRING
A string is a sequence of characters, so a for loop walks through it letter by letter.
for letter in "snek":
print(letter.upper())S
N
E
K
THE ACCUMULATOR PATTERN
The most useful loop in practice: start with an empty result, then add to it on every pass.
scores = [12, 7, 30]
total = 0
for s in scores:
total = total + s
print("Total:", total)Total: 49
Note that print is not indented, so it runs once, after the loop has finished.
for i in range(3):
print(i * 2)range(3) gives 0, 1, 2. Each is doubled: 0, 2, 4. It stops before 3, so there is no 6.BREAK AND CONTINUE
break leaves the loop early. continue skips to the next item.
for n in [4, 9, -1, 6]:
if n < 0:
break
print(n)4
9
for n in [1, 2, 3, 4, 5]:
if n % 2 == 0:
continue
print(n)1
3
5
NEED THE POSITION TOO? ENUMERATE()
for place, name in enumerate(["Ana", "Ivo", "Mia"], start=1):
print(place, name)1 Ana
2 Ivo
3 Mia
COMMON BEGINNER MISTAKES
for x in items without : is a SyntaxError.print by accident and the total is printed on every pass instead of once.range(5) is 0 to 4, five numbers in total.word = "python"
count = 0
for ch in word:
if ch in "aeiou":
count += 1
print(count)python is in "aeiou": the o. (Python does not count y as a vowel here.)PRACTICE IT, DON'T JUST READ IT
Loop Lagoon in Snekcade is built around loops: predict what prints, put lines in order, then write loops that run for real on your phone. It is free.
PLAY LOOP LAGOON ▸FAQ
What does range(5) do in Python?
It produces the numbers 0, 1, 2, 3 and 4: five numbers, starting at 0 and stopping before 5.
What is the difference between a for loop and a while loop?
A for loop goes through a known collection (a list, a string, a range). A while loop keeps going as long as a condition stays true, which is useful when you do not know in advance how many times to repeat.
How do I get the index in a Python for loop?
Use enumerate: for i, item in enumerate(items). It gives you the position and the item together.