02.2 - Loops: for, while, break, continue, else
The for Loop
The for loop iterates over any iterable (list, string, range, dict, file…).
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char)
# Iterate over a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
range() Function
range() generates a sequence of integers without creating a list in memory.
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # with step
range(5) # 0, 1, 2, 3, 4
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(10, 0, -1) # 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
# Convert to list
list(range(5)) # [0, 1, 2, 3, 4]
# Sum of 1 to 100
total = sum(range(1, 101)) # 5050
Useful for Loop Patterns
enumerate() — Index + Value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# Start from 1
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
zip() — Multiple Iterables in Parallel
names = ["Alice", "Bob", "Charlie"]
scores = [92, 87, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 92
# Bob: 87
# Charlie: 95
reversed() and sorted()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
for n in reversed(numbers):
print(n) # 6, 2, 9, 5, 1, 4, 1, 3
for n in sorted(numbers):
print(n) # 1, 1, 2, 3, 4, 5, 6, 9
for n in sorted(numbers, reverse=True):
print(n) # 9, 6, 5, 4, 3, 2, 1, 1
Iterating Over Dictionaries
person = {"name": "Alice", "age": 30, "city": "Montreal"}
# Keys only (default)
for key in person:
print(key)
# Values only
for value in person.values():
print(value)
# Keys and values
for key, value in person.items():
print(f"{key}: {value}")
The while Loop
while repeats as long as a condition is True.
count = 0
while count < 5:
print(count)
count += 1
# 0, 1, 2, 3, 4
⚠️ Always ensure the condition eventually becomes False — or use break — to avoid infinite loops.
# Infinite loop pattern (controlled with break)
while True:
user_input = input("Command (quit to exit): ").strip()
if user_input == "quit":
break
print(f"You entered: {user_input}")
Loop Control: break, continue, pass
| Statement | Effect |
|---|---|
break | Exit the loop immediately |
continue | Skip current iteration, continue with next |
pass | Do nothing — placeholder |
# break — stop when found
numbers = [1, 3, 5, 8, 11, 13]
for n in numbers:
if n % 2 == 0:
print(f"First even: {n}")
break
# continue — skip odd numbers
for i in range(10):
if i % 2 != 0:
continue
print(i) # 0, 2, 4, 6, 8
# pass — placeholder for empty blocks
for item in range(5):
pass # TODO: implement later
Loop else Clause
Python's for and while loops have an optional else clause that runs only if the loop completed without break:
# Search for a prime
numbers = [4, 6, 8, 9, 11, 15]
for n in numbers:
for i in range(2, n):
if n % i == 0:
break
else:
print(f"{n} is prime!")
# 11 is prime!
# While with else
attempts = 0
while attempts < 3:
password = input("Password: ")
if password == "secret":
print("Access granted!")
break
attempts += 1
else:
print("Too many failed attempts — locked!")
Nested Loops
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} × {j} = {i*j}", end=" ")
print() # newline after each row
# 1 × 1 = 1 1 × 2 = 2 1 × 3 = 3
# 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6
# 3 × 1 = 3 3 × 2 = 6 3 × 3 = 9
for vs while — When to Use
| Situation | Use |
|---|---|
| Iterating over a collection | for |
| Counting a fixed number of times | for + range() |
| Unknown number of iterations | while |
| User input validation | while True + break |
| Search (stop when found) | for + break |
Pythonic Loops
# ❌ Non-Pythonic: using index manually
for i in range(len(fruits)):
print(fruits[i])
# ✅ Pythonic: iterate directly
for fruit in fruits:
print(fruit)
# ❌ Non-Pythonic: manually tracking index
i = 0
for fruit in fruits:
print(f"{i}: {fruit}")
i += 1
# ✅ Pythonic: enumerate()
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
Key Vocabulary
| Term | Definition |
|---|---|
| Iterable | Any object that can be looped over (list, str, range, dict…) |
range() | Generates an integer sequence without storing it in memory |
enumerate() | Returns (index, value) pairs when iterating |
zip() | Pairs elements from multiple iterables |
break | Immediately exits the innermost loop |
continue | Skips the rest of the current iteration |
else on loop | Executes only if the loop completed without break |
| Infinite loop | A while True loop that only exits via break |
Summary
forloops iterate over any iterable — lists, strings, ranges, dictsrange(start, stop, step)generates integer sequences efficientlyenumerate()gives both index and value;zip()pairs multiple iterableswhileloops run as long as a condition is True — always provide an exitbreakexits a loop;continueskips to the next iteration- The
elseclause on a loop executes only when nobreakoccurred
📄️ 02.1 - Conditional Statements
Control program execution with if/elif/else, match/case, ternary expressions, and guard clauses
📄️ 02.2 - Loops: for & while
Master Python iteration with for loops, while loops, range(), enumerate(), zip(), and loop control statements
📄️ 02.3 - Comprehensions
Write concise, Pythonic data transformations with list comprehensions, dict comprehensions, set comprehensions, and generator expressions
📄️ Lab - Module 02
Build a complete number guessing game using conditions, loops, and comprehensions
📄️ Quiz - Module 02
30 questions on conditions, loops, break/continue, and comprehensions