3.1 for Loops, while Loops, range(), enumerate() & zip()
Repeat work without repeating code! Master for loops, range(start, stop, step), while loops, break vs continue, and the two Pythonic helpers every fresher should learn early: enumerate() and zip().
1. Why Loops? (The Conveyor-Belt Analogy)
Imagine you have to stamp 1,000 envelopes. Would you write 1,000 separate lines of print("Stamped!")? Of course not!
A loop puts your data on a conveyor belt and runs the same block of code automatically for every item:
- Use a
forloop when you know what you're iterating over (a range of numbers, every letter in a string, every item in a list). - Use a
whileloop when you want to keep repeating until a condition changes (like waiting for a user to type"quit"or guessing a secret number).
2. Mastering for Loops & range(start, stop, step)
Just like string slicing, range(start, stop, step) starts at start and stops right before stop:
# 1) range(stop) -> 0, 1, 2, 3, 4
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# 2) range(start, stop, step) -> 1, 3, 5, 7, 9
for n in range(1, 10, 2):
print(n, end=" ") # 1 3 5 7 9
# 3) Counting backwards!
for n in range(5, 0, -1):
print(n, end=" ") # 5 4 3 2 1
Iterating Directly Over Items (The Pythonic Way!)
You don't need index numbers just to read characters or items:
for ch in "CAT":
print(ch)
# C
# A
# T
3. while Loops & The Infinite-Loop Trap
A while loop checks its condition before every turn. Golden rule: something inside the loop MUST eventually make the condition False, otherwise your program loops forever!
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1 # ← Crucial! Without this, countdown stays 3 forever!
print("Liftoff!")
(If you ever trigger an accidental infinite loop in your terminal, press Ctrl + C to stop it immediately!)
4. Loop Control: break vs. continue
break= Emergency Exit — immediately stops the entire loop and jumps to the line after the loop.continue= Skip This Turn — skips the rest of the current iteration and jumps straight to the next item.
# Print only odd numbers from 1 to 5, stopping if we hit 4
for n in range(1, 6):
if n % 2 == 0:
continue # Skip even numbers
print(n) # Prints 1, 3, 5
5. Two Pythonic Superpowers: enumerate() & zip()
Freshers coming from C/Java often write ugly for i in range(len(items)): loops. In Python, use these two built-in helpers instead:
enumerate() — Get BOTH Index and Value Cleanly
fruits = ["apple", "banana", "mango"]
for idx, fruit in enumerate(fruits, start=1):
print(f"{idx}. {fruit}")
# 1. apple
# 2. banana
# 3. mango
zip() — Walk Two Lists Side-by-Side
names = ["Aarav", "Riya", "Kabir"]
scores = [92, 88, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Aarav: 92
# Riya: 88
# Kabir: 95
6. Interactive Trace: Running Sum with a for Loop
Step through how a loop accumulates a running total (total += num):
Quick Quiz: Module 3.1 — Loops & Iteration
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.