Control Flow
Checking access...
Control flow determines the order in which your code executes.
Conditionals: if, elif, else
score = 85
if score >= 90: grade = "A"elif score >= 80: grade = "B" # This runs (85 >= 80)elif score >= 70: grade = "C"else: grade = "F"
print(f"Grade: {grade}") # Grade: BTruthiness in Conditions
# Values that evaluate to False:# 0, 0.0, "", None, [], {}, (), set(), False
name = ""if not name: print("Name is empty") # This runs
items = []if items: # False for empty collections print("Has items")else: print("No items")Ternary Expression
age = 20status = "adult" if age >= 18 else "minor"# status = "adult"The match Statement (Python 3.10+)
Structural pattern matching — like switch on steroids:
def describe(value): match value: case 0: return "Zero" case 1 | 2 | 3: return "Small number" case int(n) if n > 100: return "Large number" case str(s): return f"String: {s}" case _: return "Something else"for Loops
# Iterating over a sequencefruits = ["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, 3): # 2, 5, 8 print(i)
# Enumerate — get index and valuefor index, fruit in enumerate(fruits): print(f"{index}: {fruit}")
# Zip — iterate multiple sequences in parallelnames = ["Alice", "Bob", "Charlie"]scores = [85, 92, 78]for name, score in zip(names, scores): print(f"{name}: {score}")while Loops
count = 0while count < 5: print(count) count += 1
# Be careful with infinite loops!while True: response = input("Type 'quit' to exit: ") if response == "quit": breakLoop Control: break, continue, else
# break — exit the loop immediatelyfor n in range(10): if n == 5: break print(n) # 0, 1, 2, 3, 4
# continue — skip to next iterationfor n in range(5): if n == 2: continue print(n) # 0, 1, 3, 4
# for/else — else runs if loop completed normally (no break)for n in range(5): if n == 10: breakelse: print("Loop completed without break") # This runs
for n in range(5): if n == 3: breakelse: print("Not reached") # Doesn't run — loop was brokenList Comprehensions
A Pythonic way to create lists:
# Traditionalsquares = []for n in range(10): squares.append(n ** 2)
# Comprehension — cleaner and fastersquares = [n ** 2 for n in range(10)]
# With conditionevens = [n for n in range(20) if n % 2 == 0]
# Nested loopspairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]Key Takeaways
if/elif/elsefor conditionals — empty collections andNoneare falsyforloops iterate over sequences — useenumerate()for indexes,zip()for parallel iterationbreakexits a loop,continueskips to the next iterationelseon loops runs only if nobreakoccurred- List comprehensions
[expr for item in iterable if cond]are Pythonic and fast match/case(3.10+) provides powerful pattern matching