Quiz 2

For Loops & range()

1571 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# For Loops & range() > **Why read this?** While loops are great for "until something happens." But many tasks are simpler: "do this for each item in a list" or "repeat 10 times." For loops handle this elegantly — they're the most common loop in Python. ## 🎯 Learning Objectives By the end of this topic, you will be...

For Loops & range()

Why read this? While loops are great for "until something happens." But many tasks are simpler: "do this for each item in a list" or "repeat 10 times." For loops handle this elegantly — they're the most common loop in Python.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Write for loops to iterate over sequences and ranges
  2. Use all three forms of range(): range(stop), range(start, stop), range(start, stop, step)
  3. Iterate directly over strings, lists, and other sequences
  4. Use the for-else clause
  5. Choose between for and while for any problem

📋 Prerequisites


📖 Core Content

10.1 What Problem Do For Loops Solve?

Intuition: "For each student in the class, take attendance." "For each number from 1 to 10, print its square." For loops let you iterate over a sequence of items cleanly — no manual indexing, no update statements, fewer bugs.

10.2 The range() Function

range() generates a sequence of numbers. It has three forms:
python
# runnable
# range(stop): 0 to stop-1
print("range(5):", list(range(5)))       # [0, 1, 2, 3, 4]
# range(start, stop): start to stop-1
print("range(2, 7):", list(range(2, 7)))  # [2, 3, 4, 5, 6]
# range(start, stop, step): start to stop-1, stepping by step
print("range(1, 10, 2):", list(range(1, 10, 2)))  # [1, 3, 5, 7, 9]
print("range(10, 0, -2):", list(range(10, 0, -2))) # [10, 8, 6, 4, 2]
Output:
python
range(5): [0, 1, 2, 3, 4]
range(2, 7): [2, 3, 4, 5, 6]
range(1, 10, 2): [1, 3, 5, 7, 9]
range(10, 0, -2): [10, 8, 6, 4, 2]
Note: range() does NOT create a list in memory (in Python 3). It generates numbers on the fly. This is why list(range(10**9)) crashes your computer but iterating with for i in range(10**9): works fine.

10.3 Basic For Loop

python
# runnable
for i in range(5):
    print(f"Iteration {i}")
Output:
pseudo
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
For loop flow: Diagram Rendering diagram

10.4 Iterating Over Sequences Directly

python
# runnable
# Over a string
for ch in "Python":
    print(f"Character: {ch}")
print("---")
# Over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")
Output:
pseudo
Character: P
Character: y
Character: t
Character: h
Character: o
Character: n
---
I like apple
I like banana
I like cherry

10.5 Worked Example 1: Sum of First N Natural Numbers

python
# runnable
n = int(input("Enter n: "))
total = 0
for i in range(1, n + 1):
    total += i
print(f"Sum 1 to {n} = {total}")
print(f"Formula check: n(n+1)/2 = {n * (n + 1) // 2}")
Output:
pseudo
Enter n: 100
Sum 1 to 100 = 5050
Formula check: n(n+1)/2 = 5050

10.6 Worked Example 2: Factorial with For Loop

python
# runnable
n = int(input("Enter n: "))
factorial = 1
for i in range(1, n + 1):
    factorial *= i
print(f"{n}! = {factorial}")

10.7 Worked Example 3: Multiplication Table

python
# runnable
num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num:2d} × {i:2d} = {num * i:3d}")
Output:
pseudo
Enter a number: 7
 7 ×  1 =   7
 7 ×  2 =  14
 7 ×  3 =  21
 7 ×  4 =  28
 7 ×  5 =  35
 7 ×  6 =  42
 7 ×  7 =  49
 7 ×  8 =  56
 7 ×  9 =  63
 7 × 10 =  70

10.8 Worked Example 4: Counting Vowels in a String

python
# runnable
text = input("Enter text: ").lower()
vowels = "aeiou"
count = 0
for ch in text:
    if ch in vowels:
        count += 1
print(f"Number of vowels: {count}")

10.9 The for-else Clause

Python's for loop can have an else block that runs ONLY if the loop completed without break:
python
# runnable
numbers = [2, 4, 6, 8, 9, 10]
for n in numbers:
    if n % 2 != 0:
        print(f"Found odd number: {n}")
        break
else:
    print("All numbers are even!")  # runs only if no break happened
# Compare: all even list
numbers2 = [2, 4, 6, 8, 10]
for n in numbers2:
    if n % 2 != 0:
        print(f"Found odd number: {n}")
        break
else:
    print("All numbers are even!")
Output:
pseudo
Found odd number: 9
All numbers are even!

10.10 Worked Example 5: Prime Number Checker

python
# runnable
num = int(input("Enter a number: "))
if num < 2:
    print(f"{num} is not prime.")
else:
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            print(f"{num} is not prime. Divisible by {i}.")
            break
    else:
        print(f"{num} is prime!")
Output:
pseudo
Enter a number: 17
17 is prime!

📐 Key Concepts Reference

range() FormGeneratesExample
range(stop)0, 1, ..., stop-1range(3) → 0,1,2
range(start, stop)start, start+1, ..., stop-1range(2,5) → 2,3,4
range(start, stop, step)start, start+step, ..., before stoprange(1,10,3) → 1,4,7
For vs While:
CriterionForWhile
Known iterations✅ Natural⚠ Possible
Unknown iterations⚠ Hard✅ Natural
Risk of infinite loopLowHigher
Iterating over sequence✅ Built-inNeeds indexing
Loop variable managementAutomaticManual

⚠️ Common Pitfalls

Pitfall 1: Modifying the Iterable Inside Loop

The mistake: for fruit in fruits: then fruits.remove(fruit) inside the loop. Why: You're changing the list while iterating over it, causing skipped items or index errors. Fix: Iterate over a copy: for fruit in fruits[:]: (slice copy).

Pitfall 2: Off-by-One with range()

The mistake: for i in range(1, n): when you want 1 through n inclusive. Fix: Remember: range(start, stop) goes UP TO but NOT including stop. Use range(1, n+1).

Pitfall 3: Forgetting That range() Starts at 0

The mistake: for i in range(5): print(i) and expecting 1-5. Fix: Either adjust logic for 0-based, or use range(1, 6).

Pitfall 4: Empty Range

The mistake: for i in range(10, 1): — the stop (1) is less than start (10), and step is positive (default 1), so this generates NOTHING. Fix: Add a negative step: range(10, 1, -1) for descending.

📝 Practice Questions

Q1: What does range(3, 10, 3) generate?
Answer: 3, 6, 9
Start at 3, add 3 each time: 3, 6, 9 (stop before 10). Q2: How many iterations?
python
for i in range(10, 0, -1):
    print(i)
Answer: 10 iterations (i = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1). Then i=0, but 0 > 0 is false (range stops before 0), so loop ends. Q3: What's the output?
python
result = 0
for i in range(1, 6):
    if i % 2 == 0:
        result += i
print(result)
Answer: 6 (2 + 4 = 6) Q4: Write a for loop that prints the squares of numbers 1 through 10.
Answer:
python
# runnable
for i in range(1, 11):
    print(f"{i}² = {i**2}")
Q5: What does this code output?
python
for ch in "PYTHON":
    if ch in "AEIOU":
        print(ch, end=" ")
Answer:
pseudo
O
Only 'O' is a vowel in "PYTHON" (Y is sometimes a vowel in English, but not in this set). Q6: Write code to compute the sum of all even numbers from 1 to 100 using a for loop.
Answer:
python
# runnable
total = 0
for i in range(2, 101, 2):
    total += i
print(f"Sum of even numbers 2 to 100: {total}")
Q7: When does the else clause of a for loop execute?
Answer: The else block runs when the loop completes normally (i.e., the loop finished iterating over all items). It does NOT run if the loop was exited via break. Q8: Write a for loop that finds the first occurrence of the letter 'z' in a string.
Answer:
python
# runnable
text = "the quick brown fox"
found = False
for i, ch in enumerate(text):
    if ch == 'z':
        print(f"Found 'z' at position {i}")
        found = True
        break
if not found:
    print("No 'z' found")
Q9: What's the difference between range(5) and range(0,5)?
Answer: Nothing! They're identical. Both generate 0, 1, 2, 3, 4. range(stop) is shorthand for range(0, stop). Q10: Write a program that prints all factors of a number.
Answer:
python
# runnable
n = int(input("Enter a number: "))
print(f"Factors of {n}:", end=" ")
for i in range(1, n + 1):
    if n % i == 0:
        print(i, end=" ")
print()

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.