Skip to content

Conditional Statements

Conditional statements let a program branch β€” run different code depending on whether a condition is true or false. Python uses if, optional elif (else-if) branches, and an optional final else. Unlike many languages, Python has no switch statement in older versions β€” chained elif (or match in 3.10+) fills that role.

age = 20
if age < 13:
category = "child"
elif age < 20:
category = "teenager"
else:
category = "adult"
print(category) # adult
# Ternary (conditional expression)
status = "even" if age % 2 == 0 else "odd"
# match statement (Python 3.10+)
match category:
case "child":
print("Welcome, kid!")
case "teenager" | "adult":
print("Welcome!")

Using = (assignment) instead of == (comparison) inside a condition β€” though Python raises a SyntaxError for this in an if statement (unlike C), the confusion still trips up beginners moving between languages, and the walrus operator := adds a new, easily-mixed-up lookalike.

# SyntaxError in Python -- can't assign inside a plain if condition
# if x = 5:
# ...
# Correct comparison
if x == 5:
...
# The walrus operator DOES assign inside a condition -- different purpose
if (n := len(data)) > 10:
print(f"{n} items, that's a lot")
  1. What keyword does Python use instead of else if?

    Answerelif.
  2. What’s the result of "yes" if 3 > 5 else "no"?

    Answer"no" β€” the condition 3 > 5 is false, so the ternary returns the value after else.
  3. Can you write if x = 5: in Python?

    AnswerNo β€” that raises a SyntaxError. Use == for comparison; assignment inside a condition requires the walrus operator :=.