Python for beginners · Lesson 6 of 15
Making decisions with if, elif and else
Compare values, run code only when a condition is true with if, choose between options with elif and else, and combine conditions with and, or, not.
So far every line of a program has run, one after another. Real programs make decisions: show a warning if the battery is low, give a discount if the customer is a member. For that you need conditions: questions whose answer is True or False.
Comparing values
Comparison operators compare two values and give back a bool: == equal, != not equal, < less than, > greater than, <= less than or equal, >= greater than or equal.
print(5 > 3)
print(5 < 3)
print(4 == 4)
print(4 != 4)
print(10 >= 10)
print("apple" == "Apple")True False True False True False
String comparison is case-sensitive: a capital A is a different character.
= stores a value, == compares two values. Writing if age = 18: is a mistake; you need if age == 18:.if and else
An if statement statement runs a block of code only when its condition is True. The line ends with a colon :, and the lines that belong to it are indented by 4 spaces. When the indentation stops, the if block is over. An else block runs when the condition is False.
balance = 40
price = 55
if balance >= price:
print("Payment accepted.")
else:
print("Not enough money.")
print(f"You need {price - balance} more.")
print("Thank you for shopping.")Not enough money. You need 15 more. Thank you for shopping.
The last line is not indented, so it runs in both cases.
More choices with elif
elif (short for else if) adds more conditions. Python checks them from top to bottom and runs only the first block whose condition is true. The final else catches everything else.
score = 72
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Score {score}: grade {grade}")Score 72: grade C
Combining conditions: and, or, not
and: true only when both sides are true.or: true when at least one side is true.not: flipsTruetoFalseand the other way round.
age = 25
has_ticket = True
is_member = False
if age >= 18 and has_ticket:
print("You can enter.")
if is_member or age < 12:
print("Your drink is free!")
else:
print("Drinks cost 3 euros.")
if not is_member:
print("Want to join the club?")You can enter. Drinks cost 3 euros. Want to join the club?
Conditions work well with input(). Cleaning the answer with strip() and lower() first means "Yes", "YES" and " yes " all count.
print("Do you want a receipt? (yes/no)")
answer = input().strip().lower()
if answer == "yes":
print("Printing your receipt...")
else:
print("No receipt.")Do you want a receipt? (yes/no) Printing your receipt...
Typed answer: Yes
✎ Exercise
A cinema charges 5 euros for children under 12, 7 euros for people aged 65 or more and 10 euros for everyone else. Set age = 70 and print the ticket price as Ticket: 7 euros (the number must come from your code).
Hint: Use if / elif / else and store the price in a variable, then print it once at the end. Try other ages too.
age = 70
# your code here
Expected output:
Ticket: 7 euros
Show a solution
age = 70
if age < 12:
price = 5
elif age >= 65:
price = 7
else:
price = 10
print(f"Ticket: {price} euros")Ticket: 7 euros
Check yourself
1. What is the difference between = and ==?
One equals sign assigns, two equals signs ask "are these equal?".
2. With x = 8, an if x > 5: block prints A, an elif x > 7: block prints B and the else: block prints C. What is printed?
Python runs only the first true branch. x > 5 is already true, so the elif is never checked.
3. What is True and False?
and needs both sides to be true. One side is false, so the result is False.