Drop links or images here to add them to the editor.

In this topic students learn to make the computer repeat lines of code, using while loops.

Learning objectives and goals

Be able to read, comprehend, trace, adapt and create Python code that:

Slide deck

The slide deck for this topic is on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

This week is focused on iteration, the code that makes the computer repeat certain lines of code. Iteration is more commonly known as looping.

A loop repeats the code inside it. There are several different types of loop, but in this course we are going to learn about conditional, or while, loops.

A while loop repeats the code inside it while the condition is true. When the computer gets to the start of the loop it checks the condition. If the condition is true the computer enters the loop and runs the code inside it. If the condition is false, the computer skips past the loop and carries on with the rest of the program.

When the computer gets to the end of the loop it goes back and checks the condition again. If the condition is still true it goes back into the loop and runs the code inside again. This keeps happening until the condition changes to become false.

To summarise, this code should be written like this:

while condition:
    Code to repeat whilst the condition above is true.

Code that runs once the condition is false and the loop has finished.

Using iteration to validate input: key points

Code examples

A loop that runs forever (Python uses the while True structure for this):

while True:
    print("Hello world!")

Repeat until the user inputs the correct answer:

print("What's the capital of France?")
answer = input()

while answer != "Paris":
    print("Incorrect! Try again")
    print("What's the capital of France?")
    answer = input()

print("Congratulations!")

A loop that uses a counter to output the numbers from 1 to 10:

counter = 1

while counter < 11:
    print(counter)
    counter = counter + 1

The user has 3 guesses to get the answer right:

guess_count = 1
print("What's the capital of France?")
answer = input()

while answer != "Paris" and guess_count < 4:
    print("Incorrect! Try again")
    print("What's the capital of France?")
    answer = input()
    guess_count = guess_count + 1

if answer == "Paris":
    print("Congratulations!")
else:
    print("You ran out of guesses")

Errors and misconceptions to watch out for

Make sure that students check for the following things: