Python
For Loops
Master iteration in Python: use for loops to traverse ranges, lists, and strings with confidence.
What Is Iteration?
Iteration means repeating a block of code multiple times. Instead of writing the same instruction over and over, we tell the computer: "do this action for each item in a collection" or "do this action a certain number of times."
Anatomy of a For Loop
How a For Loop Executes
The range() Function
range() generates a sequence of integers. It is the most common way to control how many times a for loop runs.
Iterating Over Lists
A list is one of Python's most versatile data structures. A for loop can walk through each element in order:
Iterating Over Strings
Strings are sequences of characters. A for loop visits each character one at a time:
for vs while
| for loop | while loop | |
|---|---|---|
| Iteration type | Definite (known count) | Indefinite (condition-based) |
| Best for | Sequences, ranges, collections | Unknown end, user input |
| Risk of infinite loop | Low | Higher |
| Variable update | Automatic (next item) | Manual (must update yourself) |
| Syntax | for x in seq: | while cond: |
Step-by-Step Approach
Example 1: Summing with range()
Calculate the sum of integers from 1 to 5 using a for loop:
Example 2: Processing a List
Given a list of test scores, print whether each score is a pass (\( \geq 60 \)) or fail:
Example 3: Counting Vowels
Count the number of vowels in a string:
Nested For Loops
You can place one for loop inside another. The inner loop runs completely for each iteration of the outer loop:
range() with Step Values
Common Mistakes
Iteration Summary
| Iterable Type | Syntax Example | Loop Variable Gets |
|---|---|---|
| range() | for i in range(5): | Each integer: 0, 1, 2, 3, 4 |
| List | for x in [10, 20, 30]: | Each element: 10, 20, 30 |
| String | for ch in "Hi": | Each character: "H", "i" |
| range(a,b,s) | for i in range(2,10,3): | 2, 5, 8 |
Question 1 of 5
What does range(3) produce?
range(3) starts at 0 by default and stops before 3, producing three values: 0, 1, 2.Question 2 of 5
How many times will this loop print?
range(2, 8) produces 2, 3, 4, 5, 6, 7. That is \( 8 - 2 = 6 \) values, so the loop prints 6 times.Question 3 of 5
What is the output of this code?
"a" * 2 = "aa". With end=" ", each doubled character is separated by a space: aa bb cc.Question 4 of 5
What value of total will this code produce?
Question 5 of 5
Which code correctly prints all even numbers from 2 to 10 (inclusive)?