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:
    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.



⚠️ 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.
Start Practice

Python for Developers

Loops with for and range()

6 tasks
Lesson progress0 / 6 tasks completed

Tasks

Practice progress

Complete a three-attempt sequence

View task

Complete the numeric sequence so the loop prints attempts 1, 2, and 3.

Requirements

  • Keep the loop body unchanged.
  • Fill only the missing stop value.

Expected output

Attempt 1
Attempt 2
Attempt 3
Code: PythonTask 1

Complete a three-attempt sequence

Change the starter code or fill in the blanks, then run it before asking Hintor.

1
2
3

Assembled code

Preview of the code that will run

Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.

Output / ConsolePreparing Python runtime...

0 / 6 tasks completed

Previous lessonBack to unitBack to track
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