Phase: 2. Control Flow & Data | Estimated time: 2 hours | Milestone Project: No
- Write
forloops to iterate over sequences - Use
range()with start, stop, and step parameters - Iterate over strings character by character
- Understand the
for-elseclause - Choose between
forandwhileloops appropriately - Use indexing patterns with
range(len())
The for loop is the most commonly used loop in Python. It's cleaner and safer than while for iterating over sequences because you don't have to manage a loop variable manually. Whether you're processing each character in a string, generating a sequence of numbers with range(), or working with collections (coming in Module 018), for is your go-to tool.
A for loop iterates over each item in a sequence:
for item in sequence:
# do something with itemThe loop variable (item) takes each value from the sequence, one at a time:
for name in ["Alice", "Bob", "Charlie"]:
print(f"Hello, {name}!")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!Strings are sequences of characters:
word = "Python"
for letter in word:
print(letter, end=" ")
# Output: P y t h o nrange() generates a sequence of integers. It's commonly used with for loops.
range(stop) — Numbers from 0 up to (but not including) stop:
for i in range(5):
print(i, end=" ")
# Output: 0 1 2 3 4range(start, stop) — Numbers from start to stop - 1:
for i in range(2, 7):
print(i, end=" ")
# Output: 2 3 4 5 6range(start, stop, step) — Numbers from start, incrementing by step:
for i in range(0, 10, 2):
print(i, end=" ")
# Output: 0 2 4 6 8
for i in range(10, 0, -2):
print(i, end=" ")
# Output: 10 8 6 4 2Key facts about range():
rangeis lazy — it doesn't create a list of all numbers in memory- The stop value is exclusive (not included)
- Default start is 0
- Step can be negative to count downward
The else clause after a for loop runs only if the loop completed without hitting break:
numbers = [1, 3, 5, 7, 9]
for n in numbers:
if n % 2 == 0:
print(f"Found an even number: {n}")
break
else:
print("No even numbers found.")
# Output: No even numbers found.(Detailed use of break comes in Module 016.)
Use for when... |
Use while when... |
|---|---|
| You know the sequence to iterate over | The number of iterations is unknown |
| You need to process items one by one | You're waiting for a condition to change |
| You want to avoid manual index management | You need a sentinel-controlled loop |
You're using range() |
You're doing input validation |
# for loop: clean iteration over a range
for i in range(10):
print(i)
# while loop: equivalent but more verbose
i = 0
while i < 10:
print(i)
i = i + 1Sometimes you need both the index and the value:
word = "hello"
for i in range(len(word)):
print(f"Index {i}: {word[i]}")
# Output:
# Index 0: h
# Index 1: e
# Index 2: l
# Index 3: l
# Index 4: o-
Modifying the sequence while iterating — Don't add or remove items from a list while looping over it (leads to skipped items). We'll cover safe patterns later.
-
Forgetting that
range(stop)excludesstop—range(10)gives 0-9, not 0-10. If you need to include 10, userange(11). -
Using
forwhen input validation needswhile— If you're waiting for a user to enter valid input, you don't know how many tries it will take. Usewhile. -
Loop variable leaking after the loop — In Python 3, the loop variable keeps its last value after the loop ends. Be aware of this.
-
Unnecessary index tracking — If you don't need the index, just iterate directly:
for item in sequence:notfor i in range(len(sequence)):.
Let's count vowels in a string using a for loop:
text = input("Enter some text: ") # Assume "Hello World"
vowels = "aeiou"
count = 0
for char in text.lower():
if char in vowels:
count = count + 1
print(f"Number of vowels: {count}") # Number of vowels: 3Now let's use range() to print a multiplication table:
n = int(input("Which multiplication table? ")) # Assume 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
# Output:
# 7 x 1 = 7
# 7 x 2 = 14
# 7 x 3 = 21
# ...
# 7 x 10 = 70for item in sequence:iterates over each element in a sequencerange(start, stop, step)generates integer sequences without creating a listrange(stop)goes from 0 to stop-1;range(start, stop)goes from start to stop-1- Strings are iterable —
for char in "hello":works for-elseruns theelseblock only if nobreakoccurred- Use
forwhen iterating over sequences; usewhilewhen waiting for a condition for i in range(len(seq)):gives you indexes; prefer direct iteration when you don't need them
Module 016: Loop Control (break, continue, loop else) — Take control of your loops with break, continue, and the loop else clause.