What is it?
Control flow determines the order Python executes code — making decisions with if/elif/else and repeating actions with for and while loops.
Why does it matter?
Mastering Python control flow — especially the Pythonic patterns like enumerate, zip, and list comprehensions — separates beginners from intermediate developers.
Master Python control flow — if/elif/else, for loops with range, while loops, break, continue, and list comprehensions.
Real-World Use Cases
- 🎓 Grade calculator - if/elif/else assigns letter grades based on score ranges.
- 📊 Data filtering - List comprehensions filter and transform data in one readable line.
- 🔄 Retry logic - while loop with a counter retries a failed API call up to 3 times before raising.
- 📋 Batch processing - for loop over files, records, or users processes each one — the backbone of any data pipeline.
if/elif/else
marks = 78
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: B
# Ternary
status = "pass" if marks >= 60 else "fail"
# Truthy/falsy — no need to compare with True/None
if not name: # empty string is falsy
print("Name required")
if data is None: # check for None specifically
print("No data")
for Loops and range()
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
for i in range(1, 6): # 1 2 3 4 5
print(i)
# enumerate — get index AND value
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}") # 1. Apple 2. Banana 3. Mango
# zip — iterate two lists in parallel
names = ["Rahul", "Priya"]
scores = [85, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
List Comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
doubled = [n * 2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
squares = {n: n**2 for n in range(1, 6)} # dict comprehension
# Flatten nested list
matrix = [[1,2,3],[4,5,6]]
flat = [num for row in matrix for num in row] # [1,2,3,4,5,6]
Q: What is the difference between break and continue?
break exits the loop entirely. continue skips the rest of the current iteration and moves to the next. Use break to stop when a condition is met; use continue to skip items that do not match a filter.
Comments (0)
No comments yet. Be the first!
Leave a Comment