for and range
range(3) gives the numbers 0, 1 and 2. A for loop takes each one in turn and runs the indented code.
for i in range(3):
print(i)0 1 2
range stops before the number you give it. range(3) never reaches 3.
Choosing where to start and stop
Give range two numbers to pick the start and the stop. A third number sets the step. A negative step counts down.
for i in range(1, 4):
print(i)
for i in range(5, 0, -2):
print(i)1 2 3 5 3 1
Try it
How many lines does this print?
for i in range(2, 5):
print(i)
Adding things up
Make a variable before the loop and add to it inside. += is a short way to write total = total + i.
total = 0
for i in range(1, 5):
total += i
print(total)10
Try it
What does this print?
total = 0
for i in range(4):
total += i
print(total)
Looping over text
A for loop can go through anything that has parts, including a string.
for letter in "cat":
print(letter)c a t
while
while keeps running as long as its condition is true. Something inside the loop has to change, or it never ends.
coins = 0
while coins < 10:
coins += 4
print(coins)12
Try it
What does this print?
n = 1
while n < 20:
n = n * 3
print(n)
Stopping early with break
for i in range(1, 11):
if i == 4:
break
print(i)1 2 3
Common mistakes
range(1, 10) stops at 9. Use range(1, 11) if you want 10 included.
A print that's indented runs every time the loop runs. One that isn't runs once, after the loop. Check which one you meant.
If the condition never becomes false, the program keeps running forever. Make sure something inside the loop moves it towards the end.
Recap
- for goes through values one at a time.
- range(stop), range(start, stop) and range(start, stop, step). The stop is never included.
- while repeats until its condition is false.
- break ends a loop early.