π Pythonπ
Day 7
Loops in Python
for and while loops, range(), break, continue, else on loops and enumerate.
π―
Learning objectives
- βUse for over any iterable
- βUse while for condition-driven loops
- βMaster range(), enumerate() and zip()
π‘ Key points
- for iterates over an iterable (list, str, dict, range, file, generator).
- while runs as long as a condition is True.
- range(start, stop, step) generates numbers lazily β great for counted loops.
- break exits early; continue skips to the next iteration.
- for/while can have an else clause β runs when the loop completes without break.
π» Code examples(5)
#1for + range
pythonfor i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1..5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
range is upper-exclusive. range(n) starts at 0. Step can be negative for countdown: range(10, 0, -1).
#2for over collections
pythonnames = ["Amit", "Priya", "Ravi"]
for name in names:
print(name.upper())
# need index too? use enumerate
for i, name in enumerate(names, start=1):
print(f"{i}. {name}")
Output
AMIT PRIYA RAVI 1. Amit 2. Priya 3. Ravi
Never write for i in range(len(x)) β always prefer enumerate.
#3while loop
pythonn = 10
while n > 0:
print(n)
n -= 1
# infinite loop with break
while True:
cmd = input("cmd> ")
if cmd == "quit":
break
while true is idiomatic. Always have a break or condition that flips β else infinite loop.
#4break, continue, else
pythonfor n in [3, 5, 7, 11]:
if n % 2 == 0:
print("Even found!")
break
print(n)
else:
print("All odd.")
Output
3 5 7 11 All odd.
The else on a for loop runs only when the loop completes without hitting break. Great for search patterns.
#5Parallel iteration with zip
pythonnames = ["Amit", "Priya", "Ravi"]
marks = [87, 92, 76]
for name, mark in zip(names, marks):
print(f"{name}: {mark}")
zip pairs items element-wise. Stops at the shortest iterable.
π― Practice
Q1. Print numbers 1 to 20 skipping multiples of 3.+
for n in range(1, 21): if n % 3 == 0: continue print(n)
Q2. When does the for/else block execute?+
When the loop finishes without executing break. Useful for 'not found' checks.
Q3. Difference between range(5) and range(0, 5)?+
Identical β both yield 0, 1, 2, 3, 4. range(5) is shorthand when start is 0.
π Notes
List comprehensions (loop shorthand)
Instead of:
squares = []
for x in range(1, 6):
squares.append(x * x)
Write:
squares = [x * x for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
More Pythonic and faster. Same idea works with {} for sets/dicts and () for generators.
Avoid modifying the collection you iterate
# β risky
for item in nums:
if item < 0: nums.remove(item)
# β
iterate over a copy or build a new list
nums = [x for x in nums if x >= 0]