Introduction
Conditional statements
Summary

Instruction

Great. Our if statement had only two options so far: either the test was passed or not. We can change this to add more possibilities.

john_age = 25
user_input = input('How old are you?')
user_age = int(user_input)

if user_age > john_age:
  print('You are older than John.')
elif user_age == john_age:
  print('You are as old as John.')
else:
  print('You are younger than John.')

Note that we added a new condition using elif (short for else if) to check if the user's age equals John's age. We can also use elif multiple times and include more conditions in the same way. As with if and else, the code after elif must be indented.

Also, we used two equals signs (==) to check for equality. Remember, a single equals sign (=) means 'assign the value of'. Confusing these two is a very common source of problems among beginner programmers.

Exercise

Write a program that will ask the user the following question: Is Sydney the capital of Australia?

  • If the user answers y, print: Wrong! Canberra is the capital!
  • If the user answers n, print: Correct!
  • If the user answers anything else, print: I do not understand your answer!

Stuck? Here's a hint!

Create a variable to keep the user's answer and use input() to get it. Then, use the following template:

if answer == 'y':
  ...
elif answer =='n':
  ...
else:
  ...