Conditional Statements
Conditional Statements
Section titled βConditional StatementsβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβ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!")Common mistake
Section titled βCommon mistakeβ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 comparisonif x == 5: ...
# The walrus operator DOES assign inside a condition -- different purposeif (n := len(data)) > 10: print(f"{n} items, that's a lot")Quick practice
Section titled βQuick practiceβ-
What keyword does Python use instead of
else if?Answer
elif. -
Whatβs the result of
"yes" if 3 > 5 else "no"?Answer
"no"β the condition3 > 5is false, so the ternary returns the value afterelse. -
Can you write
if x = 5:in Python?Answer
No β that raises aSyntaxError. Use==for comparison; assignment inside a condition requires the walrus operator:=.