Loops in Python: while & for with range()
Loops automate repetitive operations, letting computers process millions of data rows in fractions of a second.
What is it?
Python provides two primary loop types: 1. `for` loop: Iterates over any sequence (list, tuple, string, or `range()`). 2. `while` loop: Executes repeatedly as long as a condition remains true.
Why is it used?
Used to process database queries, iterate over student rosters, generate report summaries, and build interactive menus.
Detailed Explanation
The `range()` Function:
• `range(stop)`: 0 up to stop-1 (e.g. `range(5)` -> 0, 1, 2, 3, 4)
• `range(start, stop)`: start up to stop-1 (e.g. `range(1, 6)` -> 1, 2, 3, 4, 5)
• `range(start, stop, step)`: increment by step (e.g. `range(0, 10, 2)` -> 0, 2, 4, 6, 8)
The `enumerate()` Function:
Provides both the index and value during loop iteration: `for index, item in enumerate(list):`.
Syntax Structure
Syntax Blueprint
for i in range(1, 6):
print(i)
while condition:
update_counter()
Code Example
PYTHON Code
# 1. for loop with range: Multiplication Table
print("=== Multiplication Table for 7 ===")
for multiplier in range(1, 11):
print(f"7 x {multiplier:2d} = {7 * multiplier:2d}")
# 2. Iterating over list with enumerate()
courses = ["HTML", "CSS", "JavaScript", "Python", "C", "C++"]
print("\n=== IGM Tutorial Roadmap ===")
for step, course in enumerate(courses, start=1):
print(f"Module {step}: {course} Tutorial")
# 3. while loop: Countdown
countdown = 3
print("\n=== Launch Countdown ===")
while countdown > 0:
print(f"{countdown}...")
countdown -= 1
print("Program Launched!")
Explanation of the Code
• `range(1, 11)` produces numbers 1 through 10 inclusive.
• `enumerate(courses, start=1)` generates 1-based index numbers alongside the course names.
• `countdown -= 1` decrements the while counter until the condition becomes False.
Expected Output
=== Multiplication Table for 7 ===
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
=== IGM Tutorial Roadmap ===
Module 1: HTML Tutorial
Module 2: CSS Tutorial
Module 3: JavaScript Tutorial
Module 4: Python Tutorial
Module 5: C Tutorial
Module 6: C++ Tutorial
=== Launch Countdown ===
3...
2...
1...
Program Launched!
Real-World Application
Used across web scraping scripts to paginate through search results and database batch processing.
Common Mistakes to Avoid
• Forgetting that `range(1, 5)` stops at 4, not 5!
• Creating infinite while loops by forgetting to increment/decrement the counter variable.
Quick Practice Challenge
Print all even numbers from 2 to 20 using `for` and `range()` with a step of 2.
Key Takeaways
• Use `for item in sequence:` to iterate over collections.
• Use `range(start, stop, step)` for numeric iterations.
• Use `enumerate()` when you need both the index and value.