agyanadda@gmail.com

Python if, elif, else and match

Control Flow 1 min read Updated Dec 4, 2026 Topic 10 of 32

if / elif / else

if condition:
    ...
elif other_condition:
    ...
else:
    ...

Only the first true block runs. elif and else are optional.

Combining conditions

Use and, or, not, and chained comparisons like 0 < x <= 100.

Conditional expression (one line)

status = "Adult" if age >= 18 else "Minor"

Truthiness

if items: is True when the list is not empty. if not name: catches an empty string.

match-case (Python 3.10+)

match compares a value against patterns — like switch in other languages, but more powerful:

  • case "start": — exact value
  • case 1 | 2 | 3: — several values
  • case _: — default (anything else)
  • Patterns can also unpack lists and dictionaries

Example

Example — Grade calculator and menu Python
marks = 82

if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"
print("Grade:", grade)

result = "Pass" if marks >= 40 else "Fail"
print(result)

command = "stop"
match command:
    case "start":
        print("Starting...")
    case "stop" | "exit":
        print("Stopping...")
    case _:
        print("Unknown command")

Output: Grade: A, Pass, Stopping...

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword checks another condition after if?

Exercise 2 True / False

In match-case, case _: acts as the default.

Exercise 3 Fill in the Blank

One-line form: x = "Yes" if ok ___ "No"

Frequently Asked Questions

Not by that name. Use if/elif for simple cases, a dictionary mapping keys to values or functions, or match-case in Python 3.10 and later.