Control Flow
~330 words ยท 2 min read
Controlling Program Flow in Python
Control flow determines which code runs and how often. Python keeps this simple and readable through indentation rather than braces or keywords.
Conditional Branching
The if/elif/else structure evaluates conditions top to bottom and runs the first block whose condition is truthy.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
For Loops
Python's for loop iterates over any iterable โ lists, strings, ranges, or anything implementing __iter__. The range() function generates number sequences without building a list in memory.
for i in range(3): # 0, 1, 2
print(i)
for ch in "hi":
print(ch) # h, then i
enumerate()
When you need both the index and the value while looping, use enumerate() instead of tracking a counter manually. It yields index/value pairs.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
While Loops
A while loop repeats as long as its condition stays truthy. Always update the loop state so it eventually terminates.
n = 5
while n > 0:
print(n)
n -= 1
List Comprehensions
A list comprehension builds a new list in a single, declarative expression. It is the Pythonic replacement for many map/filter patterns.
squares = [x * x for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]
Readability first: if a comprehension spans multiple conditions or nested loops, a regular
forloop is often clearer. Comprehensions shine for simple, one-line transforms.
The for-else Construct
Python allows an else clause on loops. It runs only when the loop completes without hitting break โ handy for search loops.
for n in [2, 4, 6]:
if n % 2 != 0:
print("odd found")
break
else:
print("all even")