Chapter 6 of 11
Doing Things Repeatedly: Loops and Iteration
Stop copying and pasting code and let Python handle repetition for you. You’ll harness the power of loops to process lists, repeat actions, and build programs that scale from a few items to hundreds with almost no extra effort.
Why We Need Loops
The Problem With Repeating Code
If you ever copy and paste the same line of code many times, it is a sign you need a loop. For example, printing 1 to 10 with 10 separate `print` calls is hard to change and easy to mess up.
What Loops Do
Loops let the computer repeat actions for you. You describe what should happen once, and the loop takes care of doing it many times, even for hundreds or thousands of items.
What You Will Learn
In this module you will learn: `for` loops for ranges, lists, strings; `while` loops for repeating while a condition is true; `break` and `continue` to control loops; and patterns for looping over lists and dictionaries.
Building on What You Know
You already know lists, dictionaries, and `if` statements. Loops combine with these so your programs can handle 3 items or 3,000 items with almost no extra work.
Your First for Loop with range()
A `for` loop lets you run a block of code once for each value in a sequence.
The built‑in `range()` function gives you a sequence of numbers. It does not create a visible list by default, but you can loop over it directly.
Example: print the numbers 1 to 5.
Looping Over Lists and Strings
Looping Over a List
A `for` loop can go through any sequence, not just numbers. For a list like `["milk", "eggs", "bread"]`, you can do:
```python
for item in shopping_list:
print("Remember to buy:", item)
```
Looping Over a String
You can also loop over a string, one character at a time:
```python
word = "cat"
for letter in word:
print("Letter:", letter)
```
Visual Picture
Picture your list or string as a row of boxes. The loop moves a pointer from box to box. The loop variable (`item`, `letter`, etc.) holds whatever is inside the current box each time.
Predict the Output: for Loops
Try to predict what each loop will print before you run similar code yourself.
- What does this print?
```python
numbers = [3, 5, 7]
for n in numbers:
print(n * 2)
```
Write your guess:
- Line 1:
- Line 2:
- Line 3:
- What about this string loop?
```python
name = "Ana"
for ch in name:
print("-" + ch + "-")
```
Write your guess:
- Line 1:
- Line 2:
- Line 3:
After you guess, run similar code in a Python environment (like an online editor or your local setup) and compare. If your guess was different, ask yourself: how is the loop variable changing each time?
while Loops: Repeat While a Condition Is True
What is a while Loop?
A `while` loop repeats as long as a condition is true. Basic pattern:
```python
while condition:
do something
```
Example: Counting
Example:
```python
count = 1
while count <= 5:
print(count)
count = count + 1
```
Avoid Infinite Loops
The condition is checked before each repeat. You must change something inside the loop so the condition becomes false, or you get an infinite loop that never ends.
Choosing for vs while
Use `for` when you know how many times to loop or you loop over a list or string. Use `while` when you loop until something happens, like until the user types "quit".
for or while?
Decide which loop type fits best.
You are writing a guessing game. The user keeps guessing a number until they get it right. Which loop is usually a better fit?
- A `for` loop over range(1, 11)
- A `while` loop that runs until the guess is correct
- Either one is fine; it makes no difference
Show Answer
Answer: B) A `while` loop that runs until the guess is correct
A `while` loop is better because you do not know how many guesses the user will need. You want to keep looping **until** the condition "guess is correct" becomes true.
Controlling Loops with break and continue
What break and continue Do
`break` stops the loop completely and jumps to the code after the loop. `continue` skips the rest of the current loop run and moves to the next one.
Example: break
```python
numbers = [1, 3, 5, 8, 9]
for n in numbers:
if n % 2 == 0:
print("First even number:", n)
break
```
Example: continue
```python
for n in range(1, 6):
if n == 3:
continue
print(n)
```
Use With Care
If you use many `break` and `continue` statements, your loop can become hard to read. Sometimes it is better to rethink the logic to keep loops simple.
Looping Over Dictionaries
Dictionaries and Loops
Dictionaries store key‑value pairs. Example:
```python
student = {"name": "Lena", "age": 15, "grade": "10th"}
```
Looping Over Keys and Values
Patterns:
- `for key in student:`
- `for value in student.values():`
- `for key, value in student.items():`
Visual Picture
Imagine the dictionary as a table: keys on the left, values on the right. A loop over `.items()` walks each row, giving you both the key and the value for that row.
Check Your Loop Logic
Test your understanding of a mixed loop example.
What does this code print? ```python scores = {"Ava": 9, "Ben": 7, "Chen": 10} for name, score in scores.items(): if score < 8: continue print(name, "passed") ```
- Everyone passed: prints all three names
- Only Ava and Chen passed
- Only Ben passed
Show Answer
Answer: B) Only Ava and Chen passed
The loop skips scores less than 8 using `continue`. Ben has 7, so he is skipped. Ava (9) and Chen (10) are printed with "passed".
Mini Project: Class Average with Loops
Use what you have learned to process a list and a dictionary.
- Start with this data:
```python
scores = [8, 9, 10, 7, 6]
student_scores = {
"Ava": 8,
"Ben": 9,
"Chen": 10,
"Dia": 7
}
```
- Tasks to try:
- Use a `for` loop over `scores` to compute the average score.
- Use a `for` loop over `student_scores.items()` to print only the students who scored 8 or more.
- Optional: Add a counter to see how many students passed.
- Plan before coding:
- Which variables do you need to keep track of totals and counts?
- Where do you update them inside the loop?
Write your solution in a Python environment, run it, and adjust if the results are not what you expect.
Review: Loops and Iteration
Flip these cards to review key ideas.
- for loop
- A loop that goes through each item in a sequence (like a range, list, or string) and runs the loop body once for each item.
- while loop
- A loop that repeats as long as its condition is true. Good when you do not know in advance how many times you will loop.
- range(start, stop, step)
- A function that produces a sequence of numbers for looping. Commonly used as range(start, stop). The sequence includes start but stops before stop.
- break
- A statement that immediately ends the nearest loop and jumps to the code after the loop.
- continue
- A statement that skips the rest of the current loop body and moves on to the next repetition of the loop.
- Looping over a dictionary
- Use `for key in d`, `for value in d.values()`, or `for key, value in d.items()` to process the keys and values in a dictionary.
- Infinite loop
- A loop that never ends because its condition never becomes false or there is no way to leave the loop. Often a bug in `while` loops.
Key Terms
- break
- A statement used inside a loop to stop the loop immediately.
- range()
- A built‑in Python function that produces a sequence of numbers, often used with for loops.
- continue
- A statement used inside a loop to skip the rest of the current iteration and move to the next one.
- for loop
- A loop that runs a block of code once for each item in a sequence such as a range, list, or string.
- iteration
- One complete run of the loop body. If a loop runs 5 times, it has 5 iterations.
- while loop
- A loop that keeps running as long as its condition is true, checking the condition before each repetition.
- dictionary iteration
- Looping over the keys, values, or key‑value pairs stored in a Python dictionary.