π Pythonπ
Day 6
Conditional Statements in Python
if, elif, else, ternary expression and match-case in Python.
π―
Learning objectives
- βWrite branching logic with if / elif / else
- βUse the inline ternary expression
- βRecognise match-case (Python 3.10+)
π‘ Key points
- Indentation defines the block β no braces. 4 spaces per level is the convention.
- elif is Python's else-if (all one word).
- Ternary form: `value_if_true if condition else value_if_false`.
- match-case (3.10+) is Python's pattern-matching, richer than a plain switch.
π» Code examples(4)
#1if / elif / else
pythonmarks = 72
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "Needs work"
print(grade)
Output
B
Colons + indentation instead of braces. First true branch runs, others skipped.
#2Ternary expression
pythonmarks = 65
result = "Pass" if marks >= 40 else "Fail"
a, b = 3, 8
biggest = a if a > b else b
Reads left to right as English. Use for simple assignments; avoid nesting.
#3Truthy checks
pythonname = ""
if name:
print(f"Hi {name}")
else:
print("No name given")
items = []
if not items:
print("Empty list")
Empty strings, empty lists, 0, None β falsy. No need to write `if len(items) > 0` β just `if items`.
#4match-case (Python 3.10+)
pythondef describe(x):
match x:
case 0:
return "zero"
case 1 | 2 | 3:
return "small"
case int() if x > 100:
return "big int"
case _:
return "other"
print(describe(2)) # small
print(describe(200)) # big int
match compares by structure. `|` matches alternatives, `_` is the default case. Powerful β but plain if-elif is still fine for simple cases.
π― Practice
Q1. Rewrite as ternary: if x > 0: sign = 1 else: sign = -1+
sign = 1 if x > 0 else -1
Q2. Does Python have a `switch` keyword?+
No traditional switch. Python 3.10+ has `match`/`case` which is a structural pattern-matching feature, more powerful than switch.
Q3. What's wrong: `if x = 5:` ?+
= is assignment, not comparison. Use == for comparison. Python raises SyntaxError β good.
π Notes
Guard clauses
Return early to keep code flat:
def grade(marks):
if not 0 <= marks <= 100:
return "Invalid"
if marks >= 90: return "A+"
if marks >= 75: return "A"
if marks >= 60: return "B"
return "C"
Compact single-line conditions
Legal but avoid for anything non-trivial:
if x > 0: print("positive")
Multi-line form is easier to read and diff.