Conditionals (if/elif/else)
Objective
Write conditional logic in Python using if/elif/else, boolean operators, and ternary expressions.
Tools & Technologies
ifelifelsebooland/or/notternary
Key Commands
if x > 0:elif x < 0:else:result = 'yes' if condition else 'no'x and y or zArchitecture Overview
flowchart TD
COND{condition is True?} -->|True| IF_BODY[if block executes]
COND -->|False| ELIF{elif condition?}
ELIF -->|True| ELIF_BODY[elif block]
ELIF -->|False| ELSE[else block]
IF_BODY --> CONT[Continue]
ELIF_BODY --> CONT
ELSE --> CONT
style COND fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
Step-by-Step Process
01
Basic if/elif/else
Standard conditional structure.
x = 10
if x > 0:
print('positive')
elif x < 0:
print('negative')
else:
print('zero')
# Compound conditions
if age >= 18 and country == 'CA':
print('eligible')
# in operator
if name in ['Alice', 'Bob', 'Charlie']:
print('known user')
02
Truthy and Falsy Values
Python coerces values to bool in conditions.
# Falsy: False, None, 0, 0.0, '', [], {}, set()
# Truthy: everything else
if name: # True if name is non-empty
print(name)
if data: # True if list is non-empty
process(data)
# Pattern: if not value to check for empty
if not errors:
print('All OK')
03
Ternary Expression
One-line conditional assignment.
# Traditional
if score >= 60:
grade = 'pass'
else:
grade = 'fail'
# Ternary
grade = 'pass' if score >= 60 else 'fail'
# Nested ternary (use sparingly)
label = 'high' if x > 100 else ('mid' if x > 50 else 'low')
Challenges & Solutions
- = is assignment, == is comparison — classic bug in conditions
- chained comparisons work in Python: 0 < x < 100 is valid
Key Takeaways
- Python has no switch statement (until 3.10 match) — use elif chains or dicts
- Short-circuit evaluation: in 'a and b', if a is False, b is never evaluated