Skip to content

Control Flow

Python conditionals use indentation instead of braces. Any expression that evaluates to a truthy or falsy value can be used as the condition.

score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # B

There is no switch statement in Python — use if/elif chains or, since Python 3.10, structural pattern matching (match/case).

Python’s for loop iterates over any iterable — a list, string, range, file, dictionary, or custom object that implements __iter__.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over characters in a string
for ch in "hello":
print(ch)

Use enumerate() when you need both the index and the value:

for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")

range(stop), range(start, stop), and range(start, stop, step) generate integer sequences without building a list in memory.

for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)

while repeats as long as its condition is truthy.

count = 0
while count < 3:
print(count)
count += 1
  • break exits the innermost loop immediately.
  • continue skips the rest of the current iteration and moves to the next.
  • The else clause on a loop runs only if the loop completed without hitting a break.
for n in [1, 3, 5, 7]:
if n % 2 == 0:
print("found even")
break
else:
print("no even number found") # this runs

Introduced in Python 3.8, := assigns a value and evaluates to that value in the same expression. It is most useful in while and if conditions to avoid repeating an expression.

data = [4, 7, 2, 9, 1]
if (largest := max(data)) > 5:
print(f"Largest value {largest} exceeds 5")
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score {score} -> Grade {grade}")
total = 0
for i in range(1, 6):
total += i
print(f"Sum 1..5 = {total}")
numbers = [1, 3, 5, 7]
for n in numbers:
if n % 2 == 0:
print(f"Found even: {n}")
break
else:
print("No even numbers found")
count = 0
while True:
count += 1
if count % 2 == 0:
continue
if count > 7:
break
print(f"odd: {count}")
data = [4, 7, 2, 9, 1]
if (largest := max(data)) > 5:
print(f"Largest value {largest} exceeds 5")
When does the `else` clause of a `for` loop execute?
What does `range(2, 10, 3)` produce?
What does the walrus operator `:=` do?
Which statement immediately ends the current loop iteration and moves to the next one?