Introduction & Syntax
Conditional Statements · Study material
Conditional statements let a program make decisions: grant a discount, reject a wrong password, assign a grade. Python's if, elif and else look simple, but tests probe the details – which branch runs when several conditions are true, which if an else belongs to, how truthiness replaces explicit comparisons, and how match-case (Python 3.10+) differs from a C-style switch. This topic covers all of that with runnable examples, then 50 practice questions run on Python 3.
On this page
- if, if-else and if-elif-else (and why order matters)
- Nested if and how indentation pairs else with if
- Truthiness, and / or / not, in, any() and all()
- The conditional expression
- match-case: literals, alternatives, guards, sequences and mappings
- Guard clauses and early return
if, elif and else
An if header ends with a colon and is followed by an indented block. Any number of elif ("else if") branches may follow, and an optional else comes last. Python tests the conditions from top to bottom and runs only the first branch whose condition is true – so put the most specific condition first. In the grading example, testing marks >= 40 first would give every student a C.
def grade(marks):
# Branches are tested top to bottom; the FIRST true one runs, the rest are skipped
if marks >= 90:
return "A+"
elif marks >= 75:
return "A"
elif marks >= 60:
return "B"
elif marks >= 40:
return "C"
else:
return "Fail"
for m in [95, 75, 62, 40, 12]:
print(m, grade(m))
95 A+ 75 A 62 B 40 C 12 Fail
Nested if
An if may sit inside another. Because Python pairs an else with the if at the same indentation, there is no "dangling else" ambiguity as in C. Deep nesting is hard to read; combining conditions with and or using elif usually flattens it.
age, has_id = 20, False
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Adult, but show an ID") # this else belongs to the INNER if (same indentation)
else:
print("Entry not allowed")
# The same logic, flattened with and – usually easier to read
if age >= 18 and has_id:
print("Entry allowed")
elif age >= 18:
print("Adult, but show an ID")
else:
print("Entry not allowed")
Adult, but show an ID Adult, but show an ID
Truthiness in conditions
A condition does not have to be a bool: Python uses the object's truth value. Write if items: instead of if len(items) > 0:, and if not name: for an empty string. Test None explicitly with is None when 0 or "" are valid values. Because and short-circuits, if user and user["name"]: is safe even when user is None.
cart = []
coupon = ""
user = None
if not cart: # Pythonic: an empty list is falsy
print("Your cart is empty")
if coupon:
print("Coupon applied")
else:
print("No coupon")
if user is None: # test None with is, not with ==
print("Please log in")
# and short-circuits, so user["name"] is never evaluated when user is None
if user and user["name"]:
print("Hello", user["name"])
Your cart is empty No coupon Please log in
The conditional expression, any() and all()
x if condition else y chooses a value in one line – ideal for simple labels, but avoid nesting more than once. all(iterable) is True when every item is truthy (and for an empty iterable); any(iterable) is True when at least one is.
temperature = 31
label = "hot" if temperature > 30 else "pleasant"
print(label)
n = -4
sign = "positive" if n > 0 else "negative" if n < 0 else "zero" # chained, read left to right
print(sign)
marks = [45, 72, 38, 90]
print("all passed" if all(m >= 40 for m in marks) else "some failed")
print("has a topper" if any(m >= 90 for m in marks) else "no topper")
hot negative some failed has a topper
match-case: structural pattern matching
Python 3.10 added match. It compares a value against patterns from top to bottom and runs the first matching case; there is no fall-through and no break. Patterns can be literals, alternatives joined with |, a capture name (which matches anything and binds it), the wildcard _, and a guard if … that must also be true.
def http_status(code):
match code:
case 200 | 201: # | joins alternatives
return "Success"
case 301 | 302:
return "Redirect"
case 404:
return "Not found"
case n if 500 <= n < 600: # capture + guard
return f"Server error {n}"
case _: # wildcard: matches anything
return "Unknown"
for code in [200, 302, 404, 503, 999]:
print(code, http_status(code))
200 Success 302 Redirect 404 Not found 503 Server error 503 999 Unknown
Patterns can also take sequences and mappings apart, which makes command parsers and JSON handling very concise. A sequence pattern must match the length (unless it has a *rest); a mapping pattern ignores extra keys.
def run(command):
match command.split():
case ["go", direction]: # a list of exactly two words, the first "go"
return f"Moving {direction}"
case ["pick", "up", *items]: # *items captures the rest
return f"Picked up {', '.join(items)}"
case ["quit" | "exit"]:
return "Goodbye"
case []:
return "Say something"
case _:
return f"Unknown command: {command}"
for c in ["go north", "pick up lamp key", "exit", "", "dance"]:
print(run(c))
order = {"item": "pizza", "size": "L", "qty": 2}
match order:
case {"item": "pizza", "size": size}: # mapping pattern: extra keys are ignored
print("Pizza, size", size)
Moving north Picked up lamp, key Goodbye Say something Unknown command: dance Pizza, size L
Trap: a bare name in a case is a capture pattern, not a comparison. case QUIT: matches everything and binds it to QUIT – Python even refuses to compile further cases after it. To compare with a constant, use a dotted name (case Commands.QUIT:) or a literal.
Common mistakes
- Writing else if – it is
elif. - Wrong branch order – a broad condition first hides the specific ones below it.
- Separate ifs where elif was meant – several branches run.
- if grade == "A" or "B": – always true; use
in. - Comparing input() with a number – "1" == 1 is False.
- Using a variable set in only one branch – NameError on the other path.
- Treating case NAME: as a comparison – it captures.
Key points to remember
- Only the first true branch of an if-elif-else chain runs.
- else pairs with the if at the same indentation.
- Conditions use truthiness; test None with is None.
- x if c else y is an expression; if is a statement.
- match-case has no fall-through; _ is the default.
- A bare name in a case captures; use literals or dotted names to compare.
- if blocks do not create a new scope.
Frequently asked questions
Does Python have a switch statement?
match-case (3.10+) covers it and much more. Before 3.10, an if-elif chain or a dictionary of values or functions was used.
Is if x == True: wrong?
It works for real booleans but is redundant and fails for truthy non-bool values. Write if x:.
Do variables created inside an if exist afterwards?
Yes. Only functions, classes and modules create scopes in Python – but if the branch did not run, the variable was never created.
Where can I learn more?
Read Python if-else and Python match-case in the Python tutorial, then practise with the exercises below.