Before you start this course, you must login to Replit

If you have forgotten your Replit account user name or password, ask your Coder Coach.


10.1 – Iteration

In this unit you will learn about: Iteration

Iteration is used to loop certain lines of code to prevent the coder having to type them again and again.

There are several different ways of doing this. We are using a conditional iteration called a while loop. This type of loop runs while a condition (or conditions) is/are true. A while loop starts with the command while followed by the condition(s) for the loop to run. The loop will only run while the condition is true, otherwise the program will skip the loop and carry on with the rest of the program. Instructions to be repeated go inside the loop, in python we do this by indenting the code.


In these tasks, you will be given one or more examples of code.

  • Look at each example, and study it carefully.
  • Write a prediction of what it will do when it runs. Your prediction should be added to the code as comments.
  • Run the code, and compare what happens to your prediction.
  • Add comments to note the differences between your prediction and what happened.

Learning Objectives/Goals

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

  • Uses conditional iteration (while loops)
  • Validates user input
  • Repeats whilst the user does not input the desired data.


Previously we have used selection to create error messages for incorrect input, using iteration allows us to get the program to repeat until we get the input that we want.

The plain English algorithm for this looks like:

  1. Get the input & store in a variable.
  2. Start the loop, set the condition to repeat whilst the input is not the same as the desired data.
  3. Print an error message.
  4. Get the input again, store in the same variable as before.
  5. End the loop
  6. Print a success message

The condition should be set to be true when the input is NOT what is acceptable.

For text input use != not equal to.

For number range use the ‘outside a range’ conditions from the selection lessons.

Students often miss the ‘get input again inside the loop’ step. If they do this, they will create an infinite loop that never ends because the variable storing the input will never be changed.

Help! My Code Does Not Work!

  • Not getting input before the loop starts
  • No colon at the end of the loop condition
  • Not getting input again inside the loop
  • Not using the same variable to store input inside the loop
  • Not indenting the code that belongs inside the loop
  • Indenting the success message to make it part of the loop