Hintor
Python Basics for Programmers

Loops with for and range()

Python for Developers/Python Basics for Programmers/

Loops with for and range()

Python

Lesson explanation

Loops with for and range()


🎯 Learning Objective

After this lesson, you will be able to:

  • Iterate directly over values in a provided sequence.
  • Use range() for numeric repetition and predict its exclusive stop value.
  • Use a step when numbers should advance by more than one.
  • Use enumerate() when both a number and a value are needed.
  • Accumulate totals and counters while a loop runs.

Short Explanation

Python for loops usually iterate over values directly:

Python
for service in services:
 
Start Practice
print
(
service
)

This is often clearer than manually managing indexes. Use range() when the problem is genuinely about numbers, positions, or a fixed number of repetitions.

range(start, stop) includes start but stops before stop. A third argument sets the step:

Python
range(2, 9, 2)

produces 2, 4, 6, and 8.

When you need a display number and the value together, enumerate(values, start=1) is usually clearer than range(len(values)).

Loops also commonly update totals or counters. Initialize the accumulator before the loop, update it inside the block, and use the final result after the loop.

The provided sequence values in this lesson are inputs for loop practice. Full list operations are covered in the data-structures unit.

💡 Tip: Start with for item in items. Reach for numeric indexes only when the index itself has meaning.


Clean Code Examples

1. Iterate over values directly

Loop variables receive each value one at a time.

Python
regions = ["us", "eu", "apac"]

for region in regions:
    print(f"Region: {region}")

Output:

TEXT
Region: us
Region: eu
Region: apac

No index is needed because the task is about the region values.

2. Generate a numeric sequence

The stop value is not included.

Python
for attempt in range(1, 4):
    print(f"Attempt {attempt}")

Output:

TEXT
Attempt 1
Attempt 2
Attempt 3

The loop stops before 4.

3. Advance with a step

The third argument controls the distance between generated values.

Python
for port in range(9000, 9005, 2):
    print(port)

Output:

TEXT
9000
9002
9004

The sequence advances by two each time.

4. Number values with enumerate()

enumerate() gives you both a counter and the current value.

Python
workers = ["api", "queue", "mailer"]

for number, worker in enumerate(workers, start=1):
    print(f"{number}. {worker}")

Output:

TEXT
1. api
2. queue
3. mailer

The displayed numbering starts at one without manual index arithmetic.

5. Accumulate a total

Initialize the accumulator before the loop.

Python
durations = [12, 18, 15]
total = 0

for duration in durations:
    total += duration

print(f"Total: {total}")

Output:

TEXT
Total: 45

Each iteration adds one duration to the running total.


NeedPreferred loop
Work with each valuefor item in items
Repeat over numbersfor number in range(...)
Number each valuefor number, item in enumerate(...)
Build a totalInitialize before the loop, update inside

⚠️ Common Mistakes

  1. Do not expect the stop value in range() to be included.
  2. Do not force an index loop when you only need each value.
  3. Do not forget to initialize an accumulator before the loop.
  4. Do not change the loop variable and expect that to update the original sequence.