Making decisions with if, elif and else
Make Python programs choose what to do with if, elif and else, compare values, combine conditions with and/or/not, and get indentation right.
🎯 By the end of this lesson you will be able to:
- Compare values with ==, !=, <, >, <= and >=
- Write if, elif and else blocks with correct indentation
- Combine conditions with and, or and not
Outline
What you'll learn and why it matters
Until now, every line of your programs ran every time. Real programs make choices: give a discount if the cart is large, show an error if a password is too short, print “Pass” or “Try again”. In this lesson your programs learn to decide.
Questions with a yes-or-no answer
A comparison asks a question that is either true or false. Python's answer is one of two special values: True or False. These are called Booleans (after the mathematician George Boole).
| Operator | Question | Example | Answer |
|---|---|---|---|
== | is equal to? | 5 == 5 | True |
!= | is not equal to? | 5 != 3 | True |
< | is less than? | 2 < 1 | False |
> | is greater than? | 10 > 3 | True |
<= | is less than or equal to? | 4 <= 4 | True |
>= | is greater than or equal to? | 3 >= 7 | False |
Strings can be compared too: "yes" == "yes" is True, but "Yes" == "yes" is False because capital letters matter.
if: do something only when a condition is true
marks = 72
if marks >= 40:
print("You passed!")
print("Well done.")
print("Results checked.")Output
You passed! Well done. Results checked.
Three details make this work:
| Detail | Why it matters |
|---|---|
The line ends with a colon : | It tells Python a block of code is coming. |
| The next lines are indented by 4 spaces | Indented lines belong to the if. They only run when the condition is True. IDLE indents automatically after a colon. |
print("Results checked.") is not indented | It is outside the if, so it always runs. |
Change marks to 30 and run it again: only Results checked. is printed.
else and elif: choosing between paths
else runs when the if condition is false. elif (short for “else if”) lets you check more conditions in order. Python runs the first block whose condition is true, and skips the rest.
marks = 72
if marks >= 85:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Try again"
print(f"Marks: {marks}, grade: {grade}")Output
Marks: 72, grade: B
With 72 marks: 72 >= 85 is false, so Python moves on; 72 >= 70 is true, so grade becomes "B" and Python jumps past every remaining branch. The order matters: if you checked >= 40 first, every passing student would get a C.
Combining conditions: and, or, not
| Word | True when | Example |
|---|---|---|
and | both sides are true | age >= 18 and has_id |
or | at least one side is true | day == "Sat" or day == "Sun" |
not | flips True and False | not is_member |
cart_total = 1200
is_member = False
if cart_total >= 1000 or is_member:
print("Free delivery!")
else:
print("Delivery costs 49.")
if cart_total >= 1000 and not is_member:
print("Join today and save 5% next time.")Output
Free delivery! Join today and save 5% next time.
Worked example: ticket prices
A museum charges ₹50 for children under 12, ₹30 for people aged 60 or over, and ₹100 for everyone else.
age = int(input("Your age: "))
if age < 12:
price = 50
elif age >= 60:
price = 30
else:
price = 100
print(f"Your ticket costs ₹{price}.")Output (you type: 65)
Your age: 65 Your ticket costs ₹30.
Practice
Guided exercise
Even or odd
Ask the user for a whole number and print whether it is even or odd.
- Read the number with
int(input(...)). - A number is even when
number % 2 == 0(remember%from lesson 3). - Use
ifandelseto print the right message.
Show the solution
number = int(input("Number: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")Output (you type: 7)
Number: 7 7 is odd.
How to get there: 7 % 2 is 1, so the condition is False and the else block runs. Try an even number to see the other branch.
Your turn
Password check
Ask for a password. If it has fewer than 8 characters print Too short. Otherwise, if it is exactly password123 print Too easy to guess. Otherwise print Password accepted.
Show the solution
password = input("Choose a password: ")
if len(password) < 8:
print("Too short")
elif password == "password123":
print("Too easy to guess")
else:
print("Password accepted")Output (you type: sunrise-tea-42)
Choose a password: sunrise-tea-42 Password accepted
How to get there: len() from lesson 4 counts the characters. The checks run in order, and only the first true branch prints.
Common mistakes
marks = 50
if marks >= 40:
print("Pass")Python stops with this error
IndentationError: expected an indented block after 'if' statement on line 2
Missing indentation after if
You see: IndentationError: expected an indented block
Fix: Indent the lines that belong to the if by 4 spaces.
Forgetting the colon
You see: SyntaxError: expected ':'
Fix: End every if, elif and else line with :.
Using = instead of == in a condition
You see: SyntaxError: invalid syntax. Maybe you meant '==' ...
Fix: Use == to compare.
Conditions in the wrong order
You see: No error, but the wrong branch runs (e.g. everyone gets grade C)
Fix: Put the most specific or highest test first, and test the boundary values.
Comparing a number with text from input()
You see: TypeError: '>=' not supported between instances of 'str' and 'int'
Fix: Convert with int() or float() first.
Recap
- Comparisons (
==,!=,<,>,<=,>=) giveTrueorFalse. if condition:runs the indented block only when the condition is true.elifandelseadd more paths; Python runs only the first true branch.- Combine conditions with
and,orandnot, and test the boundary values.
Key terms
- Boolean
- A value that is either True or False.
- Condition
- An expression that is True or False, used to decide what runs.
- Indentation
- Spaces at the start of a line. In Python they show which lines belong to a block.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. What does this print? x = 15 if x > 10: print("big") elif x > 5: print("medium") else: print("small")
2. Which line correctly checks whether `answer` is "yes"?
3. `age = 20` and `has_ticket = False`. What is `age >= 18 and has_ticket`?
4. Which lines run only when the `if` condition is true?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.