Board Formulas
🐍 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
python
for 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
python
names = ["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
python
n = 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
python
for 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
python
names = ["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]