Lessons / Python / Unit 3

Loops

Loops let you repeat code. Python's for loop goes through a sequence of values one at a time, and while repeats until a condition becomes false.

Python · Unit 3 of 5 · about 4 minutes

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)
It prints 2, 3 and 4. range stops before 5.

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)
range(4) is 0, 1, 2, 3. Added together that's 6.

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)
n goes 1, 3, 9, 27. At 27, n < 20 is false, so the loop stops.

Stopping early with break

for i in range(1, 11):
    if i == 4:
        break
    print(i)
1
2
3

Common mistakes

Expecting range to include the last number

range(1, 10) stops at 9. Use range(1, 11) if you want 10 included.

Indenting the wrong line

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.

A while loop that never ends

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.