Guidelines

How to Create a Range of Numbers in Python

The range() function in Python is used to generate a sequence of numbers.

It is mainly used with a for loop to repeat a block of code a specified number of times or to generate a series of consecutive numbers.


How do you use the range function?

The range() function can be used in three different ways as shown below.


Single Argument

range(n) creates a sequence of numbers from 0 to n-1.

For example, range(5) generates numbers from 0 to 4 (0, 1, 2, 3, 4).

Outputs numbers from 0 to 4
for i in range(5): print(i)

Two Arguments

range(start, stop) generates numbers from start to stop-1.

For example, range(1, 5) generates numbers from 1 to 4 (1, 2, 3, 4).

Outputs numbers from 1 to 4
for i in range(1, 5): print(i)

Three Arguments

range(start, stop, step) generates numbers from start to stop-1 with a step interval.

For example, range(1, 10, 2) generates numbers from 1 to 9, increasing by 2 each time (1, 3, 5, 7, 9).

Outputs numbers from 1 to 9, increasing by 2
for i in range(1, 10, 2): print(i)

As shown, the range function is useful in a for loop to repeat a block of code a specific number of times or to create a sequence of numbers.

Example of specifying repetition count
for i in range(100): ... # Repeat code block 100 times
Mission
0 / 1

When the range() function takes 2 arguments, the second value is not included in the number generation range.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result