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

Every program you have written so far runs each line at most once. Python starts at the top, works its way down, and stops at the bottom. Selection lets it skip a few lines on the way, but nothing is ever done twice.

Real programs repeat things all the time. A quiz keeps asking until you answer correctly, a game keeps taking turns until somebody wins, a countdown keeps printing numbers until it reaches zero. Code that makes the computer repeat the same lines is called iteration, and it is more commonly known as looping.

The while statement

There are several kinds of loop. The one this topic is about is the conditional loop, written with the keyword while. It repeats the code inside it while a condition is true:

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

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

That shape should look familiar, because it is put together exactly like an if:

  1. The keyword while, followed by a condition. The condition is an ordinary Boolean check, the same kind you wrote after an if, and it comes back True or False.
  2. A colon at the end of the while line.
  3. One or more indented lines underneath. Those lines are the body of the loop: the code that gets repeated.

The one thing that is genuinely new is what happens at the bottom of the body. An if runs its branch once and moves on. A while goes back up to the top and checks the condition again.

What the computer actually does

When the computer reaches a while line, it checks the condition.

Drawn as a flowchart, that is a circle rather than a straight line:

Start Condition True Run the indented code Go back and check the condition again False Carry on with the rest of the program

Notice that the condition is checked before the body runs, every single time round. If it is already false the very first time, the body never runs at all, and the program carries straight on as though the loop were not there.

Checking an answer with a loop

Here is the classic use of a while loop: keep asking a question until the user gets it right.

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

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

print("Correct!")

There are four things worth pointing at in those nine lines.

The first question is outside the loop. It comes before the while, so it runs once, before the loop starts. It has to: the condition looks at answer, so answer has to exist before the condition can be checked.

The condition says what you do not want. answer != "Paris" is true exactly when the user has got it wrong. That is the usual shape for this kind of loop: it keeps going while the input is not what you are after, and it stops as soon as it is.

All three lines inside the loop are indented. The error message, the second question, and the line that reads the answer all belong to the body, so they are repeated. Do not forget the colon at the end of the while line.

The last line is not indented. print("Correct!") sits outside the loop, so it runs once, after the loop has finished. And by the time the loop has finished, the condition must be false, so the answer must be Paris.

If the user types London, then Rome, then Paris, the program outputs this:

What is the capital of France?
Incorrect! Try again.
What is the capital of France?
Incorrect! Try again.
What is the capital of France?
Correct!

What makes a loop end

A loop ends when its condition turns out to be false. Nothing else stops it.

So a loop only ends if something inside the body changes the data the condition looks at. In the example above that something is the second input line: it puts a new value into answer, so the next check can produce a different result.

That is the one rule to remember about writing loops:

Every while loop needs three things: a condition that is true to begin with, a body that gets repeated, and something inside that body that can eventually make the condition false.

Loops that never end

A loop whose condition never becomes false is called an infinite loop. It keeps going for as long as you let it. Sometimes that is exactly what you want, and Python has a condition that is deliberately always true:

while True:
    print("Hello world!")

True is not a check on anything, so it cannot ever turn into False. That loop prints Hello world! forever.

Far more often, though, an infinite loop is a bug, and there is one particular version of it that catches nearly everybody. Look carefully at this:

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

while answer != "Paris":
    print("Incorrect! Try again.")

print("Correct!")

The second question and the second input line are gone. Everything else is the same, and the code is perfectly valid Python. But if the user types London, then answer holds "London", and nothing in the body ever changes it. The condition is true, it will be true next time round, and it will still be true a million times round. The user never gets another chance to type anything, so Incorrect! Try again. scrolls down the screen until the program is stopped by force.

If your program is checking what the user typed, the question and the input() call have to appear twice: once before the loop, to get the first answer, and once inside the loop, to get the next one. Leaving out the pair inside is the most common loop bug there is.

Try it yourself

Run the code below. Type London, then Rome, then Paris, and watch how many times the three lines inside the loop are repeated. Then run it again and type Paris straight away, so that the body never runs at all.

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

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

print("Correct!")

Two more things to try once that makes sense. Run it again and type paris with a small p: the comparison is case sensitive, so that counts as a wrong answer. Then move the last line four spaces to the right, so that it is indented like the three lines above it. Work out why Correct! is now printed every time round the loop, even straight after a wrong answer, and why it is not printed at all when the user types Paris first time.

Do not delete the input line inside the loop to see what happens. A loop with nothing to stop it keeps running, and the only way out is to reload the page.

Help! My code doesn't work!

Make sure that you check for the following things:

  • Iteration begins with while.
  • The while line has a condition.
  • The while line has a colon (:) at the end.
  • All the code you want to repeat is indented after the while, and all of it by the same amount. Never mix tabs and spaces in one file.
  • Any code that should run once the loop has finished is not indented.
  • Something inside the loop changes the data the condition checks, so that the loop can end.
  • You have used a double equals (==) or a != in the condition. A single = stores data in a variable.