Making Decisions in Code
Conditionals let your program take different paths based on data. Python uses indentation โ no curly braces. The colon at the end of the condition is mandatory.
temperature = 35
# Basic if
if temperature > 30:
print("It's hot outside")
print("Stay hydrated")
# if/else
if temperature > 30:
print("Hot")
else:
print("Not hot")
# if/elif/else โ multiple conditions
if temperature >= 35:
print("Very hot โ danger zone")
elif temperature >= 25:
print("Warm โ comfortable")
elif temperature >= 15:
print("Cool โ grab a jacket")
elif temperature >= 0:
print("Cold โ dress warmly")
else:
print("Freezing โ stay inside")Indentation is Syntax
Python uses indentation (4 spaces) to define code blocks. Unlike other languages, this isn't just style โ it's how Python knows what's inside an if/else. Mixing spaces and tabs causes IndentationError. Use spaces, 4 per level.
Comparison and Logical Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 3 < 5 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 4 <= 5 | True |
is | Same object (identity) | x is None | depends |
in | Membership test | "a" in "cat" | True |
not in | Not member | 5 not in [1,2] | True |
age = 25
has_id = True
# and โ BOTH must be true
if age >= 18 and has_id:
print("Entry allowed")
# or โ AT LEAST ONE must be true
if age < 12 or age >= 65:
print("Discounted ticket")
# not โ inverts boolean
if not has_id:
print("You need ID")
# Chained comparisons โ Python's unique feature!
score = 75
if 60 <= score < 80:
print("Grade: B") # More readable than: 60 <= score and score < 80
# Short-circuit evaluation
# 'and' stops at first False
# 'or' stops at first True
x = None
if x is not None and x > 0: # Safe โ stops at 'x is not None' if x is None
print(x)Ternary Operator
A compact one-liner for simple if/else assignments:
# Syntax: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"
# Useful in list comprehensions and assignments
numbers = [1, -2, 3, -4, 5]
abs_nums = [n if n >= 0 else -n for n in numbers]
# [1, 2, 3, 4, 5]
# Can be nested (but avoid for readability)
grade = "A" if score >= 90 else "B" if score >= 80 else "C"Pattern Matching (Python 3.10+)
The match statement โ Python's answer to switch/case โ with powerful pattern matching:
command = "quit"
match command:
case "quit" | "exit" | "q":
print("Goodbye!")
case "help":
print("Available commands: quit, help, status")
case "status":
print("All systems running")
case _:
print(f"Unknown command: '{command}'")
# Pattern matching on structure (powerful!)
point = (0, 5)
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):
print(f"Point at ({x}, {y})")
# Match with guard conditions
value = 42
match value:
case n if n < 0:
print("Negative")
case 0:
print("Zero")
case n if n > 0:
print(f"Positive: {n}")Common Patterns
# Guard clause โ return early to avoid nesting
def process_order(order):
if order is None:
return "No order provided"
if not order.get("items"):
return "Order has no items"
if order.get("total", 0) <= 0:
return "Invalid total"
# Happy path โ no deep nesting
return f"Processing order: {order}"
# Boolean as index (Pythonic trick)
value = 42
signs = ["negative", "non-negative"]
print(signs[value >= 0]) # "non-negative"
# Walrus operator := (Python 3.8+) โ assign and test in one expression
import re
text = "Phone: 555-1234"
if match := re.search(r'\d{3}-\d{4}', text):
print(f"Found: {match.group()}") # Found: 555-1234Key Takeaways
- Indentation is mandatory: 4 spaces per level โ it's syntax, not style
- Chained comparisons:
0 < x < 10works natively and reads naturally - Short-circuit evaluation: use for safety checks (
x is not None and x.method()) - Ternary for simple cases:
x if condition else yโ don't overuse - Guard clauses over nesting: return early to keep code flat and readable
Practice Exercises
- Write a grade calculator: score 0-100 โ letter grade (A: 90+, B: 80+, C: 70+, D: 60+, F: below 60).
- Write code to check if a year is a leap year. Rules: divisible by 4, but not 100, unless also by 400. (2000 = leap, 1900 = not, 2024 = leap)
- Write a basic login check: username "admin" AND password "secret123" โ success; else print "Invalid credentials".
- Rewrite the grade calculator using a
matchstatement (Python 3.10+).