The for loop with range()
Learn how to repeat code execution efficiently
The For Loop
Loops are one of the most important concepts in programming. They allow you to execute a block of code repeatedly — a fixed number of times, or over a collection of values.
The Idea Behind for
The original purpose of a for loop is to traverse a sequence — go through each element one by one and do something with it. In Python, the for loop is built around this idea:
The most natural sequence to loop over is a list — for example, a list of numbers or names. We will cover lists in detail in the next module. For now, we will use range() — a built-in function that generates a sequence of numbers on the fly.
The range() Function
range() produces a sequence of integers. You can loop over it directly with for:
Output:
Note that range(5) generates numbers from 0 up to, but not including, 5. This is called a half-open interval — [0, 5) in mathematical notation. Zero-based indexing like this is standard in programming and you will get used to it quickly.
range() with a Start Value
By default range() starts at 0. You can pass a custom start:
The general form is range(start, stop) — generates integers from start up to, but not including, stop.
range() with a Step
The third argument controls the step — how much i increases after each iteration:
The general form is range(start, stop, step).
Step can be any positive integer:
Counting Down with a Negative Step
Passing a negative step makes the loop count downward. In this case start must be greater than stop:
Summary of range() Signatures
| Call | Generates |
|---|---|
range(n) |