The if Statement
age = 18
if age >= 18:
print("You are an adult")
if-else
temperature = 25
if temperature > 30:
print("It's hot outside")
else:
print("It's comfortable")
if-elif-else
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: C
Nested if Statements
x = 15
if x > 0:
if x % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Non-positive number")
Ternary Operator (Conditional Expression)
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Nested ternary (use sparingly!)
n = 0
sign = "positive" if n > 0 else "negative" if n < 0 else "zero"
print(sign) # zero
Pattern Matching (match-case) โ Python 3.10+
command = "quit"
match command:
case "quit":
print("Quitting...")
case "help":
print("Available commands: quit, help, run")
case "run":
print("Running...")
case _:
print(f"Unknown command: {command}")
Match with Guards
point = (3, 4)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On x-axis at {x}")
case (0, y):
print(f"On y-axis at {y}")
case (x, y) if x == y:
print(f"On diagonal at {x}")
case (x, y):
print(f"Point at ({x}, {y})")
Exercises
Exercise 1: FizzBuzz
For numbers 1โ20, print "Fizz" if divisible by 3, "Buzz" if by 5, "FizzBuzz" if by both, else the number.
Solution:
for i in range(1, 21):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Exercise 2: BMI Calculator
Calculate BMI = weight(kg) / height(m)ยฒ. Classify:
- < 18.5: Underweight
- 18.5โ24.9: Normal
- 25โ29.9: Overweight
- โฅ 30: Obese
Solution:
weight = 70 # kg
height = 1.75 # meters
bmi = weight / height ** 2
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
print(f"BMI: {bmi:.1f} โ {category}") # BMI: 22.9 โ Normal
Exercise 3: Traffic Light
Write a match statement for traffic light colors: Red (stop), Yellow (slow down), Green (go).
Solution:
light = "green"
match light:
case "red":
action = "Stop"
case "yellow":
action = "Slow down"
case "green":
action = "Go"
case _:
action = "Unknown signal"
print(action) # Go