Conditionals
if, elif, else — make decisions in code
Skills taught: python.if, python.elif, python.else, python.ternary
if, elif, else
age = 20
if age >= 18:
print('Adult')
else:
print('Minor')
# → Adult
# Multiple conditions with elif
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
Truthy and falsy values
# These are ALL falsy
if not 0: print('0 is falsy')
if not '': print('empty string is falsy')
if not []: print('empty list is falsy')
if not {}: print('empty dict is falsy')
if not None: print('None is falsy')
# Practical use: check if a value exists
name = ''
if name:
print(f'Hello, {name}')
else:
print('No name provided')
# → No name provided
# Check multiple conditions
password = 'abc123'
if len(password) >= 8 and any(c.isdigit() for c in password):
print('Password is strong')
else:
print('Password too weak')
# → Password too weak (length < 8)
Ternary expression
# ternary: value_if_true if condition else value_if_false
age = 20
status = 'adult' if age >= 18 else 'minor'
print(status) # adult
# Use in f-string
stock = 0
print(f'Item is {"in stock" if stock > 0 else "out of stock"}')
# → Item is out of stock
# Python 3.10+ — match/case (structural pattern matching)
command = 'quit'
match command:
case 'quit':
print('Quitting...')
case 'help':
print('Showing help...')
case _: # default (like else)
print(f'Unknown command: {command}')
Frequently Asked Questions
Can I use tabs for indentation?
Technically yes, but don't mix tabs and spaces — it causes IndentationError in Python 3. The standard (PEP 8) is 4 spaces. Configure your editor to insert 4 spaces when you press Tab.
Is there a switch statement in Python?
From Python 3.10+: yes, match/case (structural pattern matching). Before 3.10, use if/elif chains or a dictionary dispatch: {key: function} patterns.