The for Loop and range()
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)In Python, a for loop does not work like a C-style for (int i=0; ...) loop. Instead, it is an iterator loop that draws items directly from any sequence.
Direct iteration over text
For loop is a statement that takes the items of a sequence one at a time and runs its body once for each item. The loop variable holds the current item.
A Python for loop visits each item of a sequence one by one, binding it to the loop variable. A string is a sequence of characters, so a loop can visit them.
word = "Code"for ch in word: print(ch)Example 1 · Checking each character of a product code
product_code = "PX-204"for ch in product_code: print(f"Character: {ch}")Character: P Character: X Character: - Character: 2 Character: 0 Character: 4
What this code does
- The loop variable
chholds one character per round. - The code has six characters, so the loop body runs six times.
There is no index variable, bounds checking, or increment line. Python hands over each character in turn. Looping over lists and other collections works the same way and comes in later modules.
Generating numbers with range()
range() is a built-in that produces whole numbers on demand. range(stop) starts at 0 and ends just before stop, so range(3) gives 0, 1 and 2.
Use the built-in range() function to generate a sequence of integers efficiently without building an entire list in memory.
for i in range(3): print(i)Example 2 · Packing orders 1 to 5
for order in range(1, 6): print(f"Order #{order} packed")Order #1 packed Order #2 packed Order #3 packed Order #4 packed Order #5 packed
What this code does
range(1, 6)starts at 1 and stops before 6, soorderis 1, 2, 3, 4, 5.- The stop value 6 is not included, which is why it is one more than the last order.
range(3) produces numbers 0, 1, and 2. Notice that the stop value 3 is exclusive.
Start, stop, and step parameters
Step is the amount added in range(start, stop, step) to move from one number to the next. A negative step counts down, and the default step is 1.
range(start, stop, step) gives full control over the generated sequence, including skipping numbers or counting in reverse.
for val in range(10, 0, -2): print(val)Example 3 · Every second day
for day in range(1, 10, 2): print(f"Day {day}")Day 1 Day 3 Day 5 Day 7 Day 9
What this code does
- The step 2 adds 2 each time: 1, 3, 5, 7, 9.
- The next number would be 11, which is past the stop value 10, so the loop ends.
Example 4 · Sum of cubes
total_cubes = 0for n in range(1, 4): cube = n ** 3 total_cubes += cube print(f"{n} cubed = {cube}")
print(f"Sum of cubes: {total_cubes}")1 cubed = 1 2 cubed = 8 3 cubed = 27 Sum of cubes: 36
What this code does
- Iterates through 1, 2, and 3 using
range(1, 4). - Calculates cubes (1, 8, 27) and sums them to 36.
Using a negative step -2 counts backwards from 10 down to 2.
Next step
Check your understanding
10 quick questions