Python · Module 03: Loops & IterationTutorial 7 of 30
All Tutorials·~1.5 hrs

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().

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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 for loop when you know what you're iterating over (a range of numbers, every letter in a string, every item in a list).
  • Use a while loop 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:

Visual: `range(start, stop, step)` Always Includes `start` and Stops BEFORE `stop`
range(1, 10, 2) → 1, 3, 5, 7, 91start ✓2345678910stop ✗Notice: step = +2 jumps over even numbers, and 10 is excluded (just like string slicing!).
PYTHON
# 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:

PYTHON
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!

PYTHON
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.
Visual: `break` (Emergency Exit) vs. `continue` (Skip This Turn Only)
if n == 3: break (Loop Stops!)12345Printed: 1, 2 (4 & 5 never run!)if n == 3: continue (Skip 3 Only)12345Printed: 1, 2, 4, 5 (only 3 skipped!)
PYTHON
# 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

PYTHON
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

PYTHON
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):

Tracing a Running Total Loop
Interactive Line-by-Line Execution Trace · Step 1 of 8
1→total = 0
2for n in range(1, 4):
3 total += n
4print(f"Sum = {total}")
Variables in Memory
total0int
Console Output
(nothing printed yet)
What just happened: Always initialize an accumulator variable (total = 0) BEFORE the loop starts.

Quick Quiz: Module 3.1 — Loops & Iteration

Q1.How many times does `for i in range(2, 10, 3):` run?
Q2.What is the difference between `break` and `continue`?
Q3.Which built-in lets you loop over a list with BOTH its index and its value?

Keep Exploring: Related Lessons & Tools

All Courses →