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 selection, condition and branch. 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 if, elif and else? Click here.

Example 1

A guessing game with three outcomes.

number = 7
print("I have thought of a number between 1 and 10")
print("Can you guess what it is?")
guess = int(input())

if guess == number:
    print("Correct!")
elif guess < number:
    print("Too Low!")
else:
    print("Too High!")

Predict what this outputs, then run it and guess 3. Run it again with 9, and a third time with 7. Each run takes a different branch, so work out which condition was true each time, and which conditions Python never even looked at.

Two more things worth deciding before you run it: what the else branch covers here, given that there is no condition on it, and why the guess has to be wrapped in int() before it can be compared with number.

Example 2

This time both numbers come from the user.

print("Please enter a number")
number1 = int(input())
print("Please enter another number")
number2 = int(input())

if number1 > number2:
    print("Number 1 is bigger than number 2")
elif number2 > number1:
    print("Number 2 is bigger than number 1")
else:
    print("Both numbers are the same")

Predict what this outputs, then run it with 4 and 9. Run it again with 9 and 4, and a third time with 5 and 5.

The two conditions here are near-mirror images of each other. Work out why the third outcome does not need a condition of its own, and what the program would do if you deleted the elif branch entirely.

Help! My code doesn't work!

Make sure that you check for the following things:

  • Selection begins with if, has as many elif branches in the middle as you need, and ends with else.
  • There is a colon at the end of each if, elif and else line.
  • Every line inside a branch is indented, and all of them by the same amount. Never mix tabs and spaces in one file.
  • The if, elif and else lines themselves are not indented.
  • There is a condition after each if and each elif.
  • There is no condition after else.
  • You have used a double equals (==) in a condition that checks whether two pieces of data are the same. A single = stores data in a variable.