Control Flow
If, Elif, Else & match
Decisions in Python: if/elif/else, nested conditions, the conditional expression, and structural pattern matching with match/case.
Python
marks = int(input("Marks: "))
if marks >= 90:
grade = "O"
elif marks >= 80:
grade = "A+"
elif marks >= 70:
grade = "A"
elif marks >= 60:
grade = "B+"
elif marks >= 40:
grade = "P"
else:
grade = "F"
print("Grade:", grade)Output
Marks: 73
Grade: ASample input is includedTry it Yourself
Key points:
- A colon
:ends the condition line; the block is the indented lines below. elif(else-if) can repeat;elseis optional and comes last.- Conditions can be any value — Python uses its truthiness.
Nested conditions and combining tests
Python
def leap_year(y):
return (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
for year in (1900, 2000, 2024, 2026):
print(year, "leap" if leap_year(year) else "not leap")
age, has_id = 20, True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Show an ID")
else:
print("Too young")Output
1900 not leap 2000 leap 2024 leap 2026 not leap Entry allowed
The conditional expression
value_if_true if condition else value_if_false — Python's version of C's ?::
Python
n = 7
parity = "even" if n % 2 == 0 else "odd"
print(f"{n} is {parity}")
print(max(3, 9), min(3, 9)) # built-ins often replace simple ifsOutput
7 is odd 9 3
match / case (Python 3.10+)
match compares a value against patterns — like C's switch, but more powerful. There is no fall-through, so no break is needed.
Python
def describe(command):
match command.split():
case ["quit"] | ["exit"]:
return "Goodbye"
case ["go", direction]:
return f"Moving {direction}"
case ["add", x, y]:
return f"{x} + {y} = {int(x) + int(y)}"
case []:
return "Say something"
case _: # the wildcard: matches anything
return f"Unknown command: {command}"
for cmd in ["go north", "add 4 5", "exit", "dance", ""]:
print(repr(cmd), "->", describe(cmd))Output
'go north' -> Moving north 'add 4 5' -> 4 + 5 = 9 'exit' -> Goodbye 'dance' -> Unknown command: dance '' -> Say something
A simple value match looks just like a switch:
Python
def day_type(day):
match day:
case "Sat" | "Sun":
return "weekend"
case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
return "weekday"
case _:
return "not a day"
print(day_type("Sun"), day_type("Wed"), day_type("Funday"))Output
weekend weekday not a day
Test yourself
4 questions · pick an answer to check it instantly
- 1
What is printed?
Pythonx = 0 if x: print("A") elif x == 0: print("B") else: print("C")0 is falsy, so the first branch is skipped andx == 0is true. - 2
What is
"pass" if 35 >= 40 else "fail"?The condition is false, so the value afterelseis chosen. - 3
In a
matchstatement, what doescase _:do?The wildcard pattern always matches. - 4
Does Python's
matchfall through to the next case like C'sswitch?There is no fall-through inmatch.