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.
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.
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?
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.
Make sure that you check for the following things:
while.while line has a condition.while line has a colon (:) at the end.while, and all of
it by the same amount. Never mix tabs and spaces in one file.==) or a != in the condition. A single
= stores data in a variable.