Nishaglobal Education logo

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.

Lesson 6 of 1425 minQuiz: 4 questions

🎯 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
  1. What you'll learn and why it matters
  2. Questions with a yes-or-no answer
  3. if: do something only when a condition is true
  4. else and elif: choosing between paths
  5. Combining conditions: and, or, not
  6. Worked example: ticket prices
  7. Practice
  8. Common mistakes
  9. Recap
  10. Quiz
  11. Mark lesson complete

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).

OperatorQuestionExampleAnswer
==is equal to?5 == 5True
!=is not equal to?5 != 3True
<is less than?2 < 1False
>is greater than?10 > 3True
<=is less than or equal to?4 <= 4True
>=is greater than or equal to?3 >= 7False

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

Python
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:

DetailWhy it matters
The line ends with a colon :It tells Python a block of code is coming.
The next lines are indented by 4 spacesIndented lines belong to the if. They only run when the condition is True. IDLE indents automatically after a colon.
print("Results checked.") is not indentedIt 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.

Python
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
marks >= 85 ?yesgrade = "A"nomarks >= 70 ?yesgrade = "B"nomarks >= 40 ?yesgrade = "C"noelsegrade = "Try again"72 stops hereThick borders: the path for marks = 72
Python checks each condition from the top. The first true condition wins and the others are skipped; else catches everything left.

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

WordTrue whenExample
andboth sides are trueage >= 18 and has_id
orat least one side is trueday == "Sat" or day == "Sun"
notflips True and Falsenot is_member
Python
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.

Python
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.

  1. Read the number with int(input(...)).
  2. A number is even when number % 2 == 0 (remember % from lesson 3).
  3. Use if and else to print the right message.
Show the solution
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
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

Forgetting to indent
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 (==, !=, <, >, <=, >=) give True or False.
  • if condition: runs the indented block only when the condition is true.
  • elif and else add more paths; Python runs only the first true branch.
  • Combine conditions with and, or and not, 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. 1. What does this print? x = 15 if x > 10: print("big") elif x > 5: print("medium") else: print("small")

  2. 2. Which line correctly checks whether `answer` is "yes"?

  3. 3. `age = 20` and `has_ticket = False`. What is `age >= 18 and has_ticket`?

  4. 4. Which lines run only when the `if` condition is true?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.