Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 5 of 22 · 4 min read

Python if, elif, else and match-case

Python conditional statements notes: if, if-else, the elif ladder, nested if, writing good conditions, the one-line ternary, match-case and common mistakes.

if: run code only when a condition is true

marks = 45
if marks >= 33:
    print("Pass")
    print("Well done")
print("Result checked")      # always runs

The lines under if are indented (4 spaces is standard). The indentation tells Python which lines belong to the if. The colon : at the end of the if line is required.

if / else: two paths

age = int(input("Age: "))
if age >= 18:
    print("You can vote")
else:
    print("Too young to vote")

Exactly one of the two blocks runs.

The elif ladder: many choices, one answer

marks = 81
if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 33:
    grade = "C"
else:
    grade = "Fail"
print(grade)       # A

Python checks the conditions from top to bottom and runs only the first one that is true. With marks = 81, the test marks >= 90 fails, marks >= 75 passes, and the rest are skipped.

Order matters. If marks >= 33 came first, every pass mark would get a C.

Nested if: a decision inside a decision

if username == "admin":
    if password == "1234":
        print("Welcome")
    else:
        print("Wrong password")
else:
    print("Unknown user")

Nesting is useful when the second question only makes sense after the first answer. Deep nesting is hard to read, so combine conditions with and when you can.

Writing good conditions

if 0 <= marks <= 100:                 # a range, in one comparison
    ...
if day == "Sat" or day == "Sun":      # repeat the variable on both sides
    ...
if day in ("Sat", "Sun"):             # shorter, and easy to extend
    ...

Truthy and falsy values

In a condition, these count as false: 0, 0.0, "" (empty string), [], {}, None and False. Everything else counts as true.

name = input("Name: ")
if name:
    print("Hello", name)
else:
    print("You did not type a name")

The conditional expression (ternary)

A short if / else that produces a value, on one line:

result = "Pass" if marks >= 33 else "Fail"
fee = 0 if age < 5 else 20

Use it for simple choices only. For anything longer, write a normal if.

match-case: choose by matching a value

match (Python 3.10 and later) compares one value against several patterns.

choice = input("Order (1-3): ")
match choice:
    case "1":
        print("Tea: Rs 10")
    case "2":
        print("Coffee: Rs 20")
    case "3" | "4":
        print("Juice: Rs 30")
    case _:
        print("Not on the menu")
  • | matches any of several values.
  • case _: is the default, like else.
  • Only one case runs; there is no fall-through.

Example: electricity bill with slab rates

units = int(input("Units used: "))
if units <= 100:
    bill = units * 3
elif units <= 200:
    bill = 100 * 3 + (units - 100) * 5
else:
    bill = 100 * 3 + 100 * 5 + (units - 200) * 7
print("Bill: Rs", bill)

Top mistakes with if statements

  1. if marks = 90: uses = instead of == (a SyntaxError).
  2. Missing colon at the end of if, elif or else.
  3. Wrong indentation, so a line runs when it should not, or an IndentationError.
  4. if day == "Sat" or "Sun": is always true, because "Sun" on its own is truthy.
  5. Putting a wide condition before a narrow one in an elif ladder.

Key points

  • if, elif and else lines end with : and their blocks are indented.
  • Only the first true branch of an elif ladder runs.
  • Empty values and 0 are falsy; everything else is truthy.
  • Use x if condition else y for short choices and match to compare one value against many.

Practice questions

1. Write a program that prints whether a number is positive, negative or zero.
n = int(input("Number: "))
if n > 0:
    print("Positive")
elif n < 0:
    print("Negative")
else:
    print("Zero")
2. What is printed when x = 15?
if x > 10:
    print("A")
elif x > 5:
    print("B")
else:
    print("C")

Only A. The first true branch runs and the rest are skipped.

3. Why is if color == "red" or "blue": a bug?

It reads as (color == "red") or ("blue"). A non-empty string is truthy, so the condition is always true. Write if color in ("red", "blue"):.

4. Rewrite in one line: if n % 2 == 0: kind = "even" / else: kind = "odd".

kind = "even" if n % 2 == 0 else "odd"

5. Write the largest of three numbers without using max().
a, b, c = 4, 9, 7
if a >= b and a >= c:
    big = a
elif b >= c:
    big = b
else:
    big = c
print(big)