Lesson Progress

0% Complete

The Python `range()`

function returns a sequence of numbers. It is commonly used as part of a `for`

loop.

`range(start, stop, step)`

`start`

– optional, default is 0`stop`

–**required**`step`

– optional, default is 1

The `range()`

function is commonly used to loop over some code a specific number of times.

```
for i in range(10):
print(i)
```

The above code will print each number in the range [0, 9] inclusive. Note that `range(10)`

begins at 0 and stops at 9 – a total of 10 numbers but not including the number 10.

`range()`

may be called with a **single bounding parameter**, as in `range(stop)`

. The returned sequence will begin at zero and count up by 1 until the bound (not including it). For example, `range(4)`

would include 0, 1, 2, and 3, but not 4.

When using **two parameters**, the function operates as `range(start, stop)`

. The `start`

parameter specifies the first number of the sequence, and `stop`

works as before by bounding the sequence. So `range(2, 5)`

would include 2, 3, and 4, but not 5.

Finally, a function call with **three parameters** is done by `range(start, stop, step)`

. The `step`

parameter specifies the incrementation between each consecutive number in the sequence, beginning at the starting number. As an example, `range(0, 6, 2)`

would include 0, 2, and 4 (6 is the upper bound, so is not included).