Loops (for & while)
Objective
Iterate with for and while loops, use built-in iteration helpers, and control loop flow with break and continue.
Tools & Technologies
forwhilerange()enumerate()zip()breakcontinue
Key Commands
for i in range(10):for i, v in enumerate(lst):while condition:breakcontinuelist(zip(a, b))Architecture Overview
flowchart TD
ITER[Iterator/Sequence] --> LOOP[for item in sequence]
LOOP -->|has item| BODY[Loop body]
BODY --> BREAK{break?}
BREAK -->|yes| EXIT[Exit loop]
BREAK -->|no| CONT{continue?}
CONT -->|yes| LOOP
CONT -->|no| LOOP
LOOP -->|exhausted| ELSE[else block\nif no break]
EXIT --> AFTER[Code after loop]
style BREAK fill:#1a1a2e,stroke:#ff4444,color:#ff4444
style ELSE fill:#1a1a2e,stroke:#ffd700,color:#ffd700
Step-by-Step Process
01
for Loop
Iterate over any iterable.
# Over range
for i in range(5): # 0 1 2 3 4
print(i)
# With start, stop, step
for i in range(0, 10, 2): # 0 2 4 6 8
print(i)
# Over list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# enumerate: index + value
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
02
while Loop & break/continue
Control flow within loops.
# Count down
n = 5
while n > 0:
print(n)
n -= 1
# break: exit loop early
for item in data:
if item == target:
print('Found!')
break
else:
print('Not found') # runs if no break
# continue: skip to next iteration
for n in range(10):
if n % 2 == 0:
continue # skip even
print(n) # only odd
03
zip and List Comprehensions
Combine and transform iterables.
# zip
names = ['Alice', 'Bob']
scores = [95, 87]
for name, score in zip(names, scores):
print(f'{name}: {score}')
# List comprehension
squares = [x**2 for x in range(10)]
even = [x for x in range(20) if x % 2 == 0]
# Dict comprehension
name_len = {name: len(name) for name in names}
Challenges & Solutions
- Modifying a list while iterating over it causes skipped items — iterate a copy
- range() is lazy (doesn't create the list) — list(range(10)) creates it
Key Takeaways
- The for...else clause is unique to Python — runs if loop wasn't terminated by break
- enumerate(lst, start=1) starts index at 1