Basic If
Run a block of code only when a condition is true:
answer = input("Is the window open? ")
if answer == "yes":
print("It's chilly in here!")
If the answer is yes, the message prints; otherwise nothing happens.
If, Elif, Else
Handle multiple possibilities. Notice the colons and indentation:
answer = input("Is the window open? ")
if answer == "yes":
print("It's chilly in here!")
elif answer == "no":
print("It's quite hot in here!")
else:
print("I'm not sure what you mean.")
“Not Equal To”
Use != for “not equal to”:
answer = input("What is the capital of Eritrea? ")
if answer != "Asmara":
print("That is incorrect! It is Asmara.")
else:
print("You got it right!")
If Statements Task 1 – Left or Right?
Ask for a direction and print a different message for each response:
direction = input("There is a path ahead. Do you turn left or right? ")
if direction == "left":
print("The path twists and turns until it ends at a cliff. Dead end!")
elif direction == "right":
print("A snake slithers across the path and bites your leg. Oh no!")
else:
print("That's not an option!")
Nested If Statements
Place an if inside another for more control (mind your indentation!):
weather = input("What is the weather like today? ")
if weather == "sunny":
heat = input("How hot is it? ")
if heat == "very hot":
print("Take some sunglasses!")
elif heat == "cool":
print("Maybe bring a light jacket.")
else:
print("Enjoy the sunshine!")
elif weather == "rainy":
print("Don't forget your umbrella!")
else:
print("Have a great day!")
If Statements Task 2 – Nested Ifs
Create your own nested-if program (e.g., favourite juice then consistency). Keep your if, elif, and else aligned and indented.
Selection with Numbers
Compare numbers with >, >=, <, <=. Combine conditions with and / or:
score = int(input("Enter the maths test score: "))
if score == 50:
print("You scored top marks!")
elif score >= 40 and score < 50:
print("You scored a great grade!")
elif score >= 20 and score < 40:
print("You did okay in the test.")
else:
print("You need to try harder next time!")
If Statements Task 3 – Fastest Lap
Record lap time is 37 seconds. React differently to the player’s time:
lap_time = int(input("Enter your lap time: "))
if lap_time < 37:
print("You have set a new record!!!")
elif lap_time >= 37 and lap_time <= 59:
print("You did well this time!")
elif lap_time >= 60 and lap_time <= 90:
print("A little slow, try to push harder!")
else:
print("Were you even trying?! Hurry up!")
If Statements Task 4 – True or False?
Ask a true/false question and print whether the answer is correct:
response = input("There are 140 million miles between Earth and Mars. TRUE or FALSE? ")
if response == "TRUE":
print("That is correct! It's really that far!")
else:
print("You got it wrong, there are indeed 140 million miles between us!")