Conditional Statements
if/elif/else
score = 85
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: B
Ternary Operator
# Conditional expression
age = 20
status = 'adult' if age >= 18 else 'minor'
# Nested ternary (avoid!)
result = 'positive' if x > 0 else 'zero' if x == 0 else 'negative'
Match-Case (Python 3.10+)
def http_status(code):
match code:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500:
return 'Server Error'
case _:
return 'Unknown'
# Pattern matching with guards
match command:
case ['quit']:
exit()
case ['go', direction] if direction in ['north', 'south', 'east', 'west']:
move(direction)
case ['get', item]:
pick_up(item)
Common Patterns
# Truthy/falsy checking
if items: # Instead of: if len(items) > 0:
process(items)
if not name: # Instead of: if name == '':
name = 'Anonymous'
# Chained comparisons
if 0 < x < 100:
valid = True
# Guard clauses
def process(data):
if not data:
return None
if not isinstance(data, list):
return None
# Main logic here
For Loops
Basic For Loop
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Using range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10): # 2, 3, ..., 9
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
for i in range(10, 0, -1): # 10, 9, ..., 1
print(i)
Enumerate
# Get index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f'{index}: {fruit}')
# Custom start index
for index, fruit in enumerate(fruits, start=1):
print(f'{index}. {fruit}')
Iterating Over Different Types
# Strings
for char in 'Hello':
print(char) # H, e, l, l, o
# Dictionaries
person = {'name': 'Alice', 'age': 30}
for key, value in person.items():
print(f'{key}: {value}')
# Only keys
for key in person:
print(key)
# Sets
unique = {1, 2, 3}
for num in unique:
print(num)
List Comprehension (Preview)
# Instead of:
squares = []
for x in range(10):
squares.append(x ** 2)
# Write:
squares = [x ** 2 for x in range(10)]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
Loop Control
# break - exit loop
for i in range(100):
if i == 5:
break # Stop at 5
# continue - skip iteration
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # 1, 3, 5, 7, 9
# pass - do nothing
for i in range(10):
if i % 2 == 0:
pass # TODO: handle later
While Loops
Basic While Loop
count = 0
while count < 5:
print(count)
count += 1
# Output: 0, 1, 2, 3, 4
While with User Input
while True:
user_input = input('Enter command: ')
if user_input == 'quit':
break
print(f'Processing: {user_input}')
Avoid Infinite Loops
# ⚠️ Dangerous: no termination condition
while True:
pass # Program hangs!
# ✅ Safe: always have a way out
while True:
user_input = input('Enter: ')
if user_input == 'quit':
break
For-Else and While-Else
# else clause runs if loop completes without 'break'
def find_item(items, target):
for item in items:
if item == target:
print(f'Found {target}')
break
else:
print(f'{target} not found')
find_item([1, 2, 3], 4) # 4 not found
find_item([1, 2, 3], 2) # Found 2
Nested Loops
# Matrix traversal
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=' ')
print()
# Output:
# 1 2 3
# 4 5 6
# 7 8 9
Loop Performance Tips
# ✅ Use enumerate instead of range(len())
for i, item in enumerate(items): # Pythonic
pass
for i in range(len(items)): # Less Pythonic
pass
# ✅ Use zip for parallel iteration
names = ['Alice', 'Bob']
ages = [30, 25]
for name, age in zip(names, ages):
print(f'{name} is {age}')
# ✅ Use any() and all()
numbers = [1, 3, 5, 7]
all_odd = all(n % 2 == 1 for n in numbers) # True
any_even = any(n % 2 == 0 for n in numbers) # False