Python

Python range(): Usage and Examples

arage.com@gmail.com

The range() function in Python is used to generate a sequence of consecutive integer values. In this article, we will provide a detailed explanation of how to use the range() function.

How to Use the range()

Parameters of the range() – start, stop, step

The range() function can accept three parameters:

  1. start (optional)
    • Specifies the starting value of the sequence. The default value is 0.
  2. stop
    • Specifies the value at which the sequence ends. This value is not included in the sequence itself.
  3. step (optional)
    • Specifies the increment between each element. The default value is 1.

Below, we will explain the meaning and usage of each parameter.

start(optional

The start parameter specifies the starting value of the sequence. By default, it is set to 0. You can specify any integer value.

For example, if you set start=5, the first value in the generated sequence will be 5.

1for i in range(5, 10):
2    print(i)

Output:

5
6
7
8
9

stop

The stop parameter specifies the value that comes immediately after the end of the sequence. In other words, the specified value is not included in the sequence.

For example, if you set stop=5, the last value in the generated sequence will be 4.

1for i in range(5):
2    print(i)

Output:

0
1
2
3
4

step(optional

The step parameter specifies the increment between each element. By default, it is set to 1.

For example, if you set step=2, the elements in the generated sequence will increase by 2.

1for i in range(1, 10, 2):
2    print(i)

Output:

1
3
5
7
9

Return Value of the range()

The range() function returns an iterator that generates a sequence of integer values within the specified range. This iterator can be used in constructs such as for loops, as demonstrated in the previous code samples.

It is also possible to directly convert the iterator into a list.

1numbers = list(range(5))
2print(numbers) # [0, 1, 2, 3, 4]

Notes and Troubleshooting for the range()

Combining with Float Values

The range() function generates a sequence of integers, so it does not support the use of float values.

1for i in range(0.5, 5.5):
2    print(i)

Output:

TypeError: 'float' object cannot be interpreted as an integer

When the start value is greater than the stop value

If the value of the start parameter in the range() function is greater than the value of the stop parameter, no sequence will be generated, resulting in an empty outcome.

When specifying 0 for the step parameter

If you specify 0 for the step parameter of the range() function, an error will occur.

記事URLをコピーしました