Skip to content

6 min read

American Corners

Loops

Teaching a robot to repeat itself

So far, every instruction you gave Python ran once. But real programs do the same thing over and over: draw four sides of a square, deal a card to each player, check every letter in a word. Writing the same line ten times would be slow and easy to get wrong. A loop lets you write the instruction once and tell Python how many times, or under what condition, to run it.

Think of the turtle as a small robot. To draw a square you want it to go forward and turn right, four times. Instead of copying those two lines four times, you wrap them in a loop. That is the whole idea: repeat a block of work without repeating yourself.

Python gives you two loops. A while loop repeats as long as something stays true. A for loop repeats once for each item in a sequence. We will meet both.

The while loop: repeat while something is true

A while loop keeps running its block for as long as a condition holds. The moment the condition becomes false, Python skips past the loop and carries on.

Here the robot counts up from 0 and stops before it reaches 3:

count = 0
while count < 3:
    print("Hello!")
    count = count + 1

This prints Hello! three times. Read it slowly. Python checks count < 3. It is true (0 is less than 3), so the block runs: it prints, then adds 1 to count. Now count is 1, still less than 3, so it runs again. When count reaches 3 the condition is false and the loop ends.

The line count = count + 1 matters. If you forget it, count stays 0 forever, the condition never turns false, and the loop never stops. That is called an infinite loop, and it is the most common while mistake. Every while loop needs something inside it that moves it toward stopping.

The for loop: once for each item

A for loop is the natural choice when you already know what you want to walk through, such as a list of words. It runs its block once for each item, handing you the item each time:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

That prints apple, then banana, then cherry. The variable x becomes each fruit in turn; you did not have to count anything.

When you want to repeat a fixed number of times, pair for with range. range(4) produces the numbers 0, 1, 2, 3, so this draws a square:

import turtle

skk = turtle.Turtle()
for side in range(4):
    skk.forward(100)
    skk.right(90)
turtle.done()

So when do you use which? Use a for loop when you know the items or the count ahead of time, which is most of the time. Use a while loop when you cannot say in advance how many rounds it will take, for example "keep asking until the player types a valid answer".

break and continue: stopping early and skipping

Sometimes you want to leave a loop before it would naturally end. break stops the loop immediately. This is how you halt a robot that would otherwise move forever:

count = 0
while True:
    print("moving")
    count = count + 1
    if count == 5:
        break

while True would run forever on its own, but break jumps out once the robot has moved five times.

continue is gentler: it skips the rest of the current round and goes straight to the next one. Here it prints only the odd numbers by skipping the even ones:

for n in range(1, 7):
    if n % 2 == 0:
        continue
    print(n)

Python also lets you attach an else to a loop. The else block runs once, after the loop finishes normally (that is, when no break stopped it):

for i in range(1, 4):
    print(i)
else:
    print("No break")

This prints 1, 2, 3, and then No break.

Check yourself

  1. In the counting example, why does the line count = count + 1 matter? What would happen to the loop if you deleted it?
  2. You want to draw a hexagon (six sides) with the turtle. Would you reach for a for loop or a while loop, and roughly what would go inside it?
  3. What is the difference between what break does and what continue does when Python reaches them inside a loop?

Where this lesson comes from

Built from

  • Programming in a Data World: Lecture 3 deck (loops) and Lecture Notebook
  • Video: 3.0 Loops

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement