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

In a predict and run task you do not write code from scratch. You start from a small piece of working code, work out what you think it will do before you run it, and then run it to check whether you were right.

This task contains two examples. Work through them in order.

Predict

For every example, study the code carefully and write down a prediction of what it will do when it runs. Your prediction should use the key terms iteration and condition. Say which lines are inside the loop and which are outside it, and explain the circumstances in which the loop will run. You can type your prediction straight into the code as a comment, on a line starting with #.

Only once you have written your prediction should you run the code and compare the result with what you expected.

Need more help with while loops? Click here.

Example 1

A question that keeps coming back until it is answered correctly.

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!")

Predict what this outputs, then run it and type London. Type Rome when it comes back, and then Paris. Run it a second time and type Paris straight away.

Before you run it, decide two things. How many times does the loop repeat when the user gets it right on the third try, and how many times when they get it right immediately? And what would happen if the second input line, the one inside the loop, were deleted?

Example 2

This one asks the user nothing at all.

counter = 1

while counter < 5:
    print("This code is inside the loop")
    counter += 1

Predict what this outputs. This time the number of repetitions is fixed, so work out exactly how many lines appear before you run it, and which values counter holds when the condition is checked.

Then predict what changes if you replace counter += 1 with counter += 2, and run it again to check.

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.