Introduction
The range() function in Python prints out a string of numbers according to the start value, end value, and jump we entered. In Python2 version, it is called xrange() function, it wasn’t until Python3 version that it was named range() function.
And we will show you how to use the range() function in Python as you go through it below. Hope you understand.
Example
Example 1: Number sequence from 1 to 4
x = range(1, 5) for i in x: print(i)
Output:
1 2 3 4
Example 2: The sequence of numbers from 3 to 12 step is 3
x = range(3, 15, 3) for i in x: print(i)
Output:
3 6 9 12
Definition
The range() function in Python prints out a string of numbers. By default, it will start at 0, step is 1 and stop at the specified number.
We can specify starting point and step.
The syntax
range(start, stop, step)
Parameter Values:
start: the starting point is an integer. By default, it is 0 (optional).
stop: the stopping point is an integer (required).
step: the step of the sequence of numbers is an integer. By default, it is 1 (optional).
More examples
Example 1:
range() combined with the list() function # Number range from 0 to 9 x = list(range(10)) print(x) # Number range from 1 to 9 y = list(range(1,10)) print(y)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Sequence of even numbers from 2 to 12
x = list(range(2,14,2)) print(x)
Output:
[2, 4, 6, 8, 10, 12]
Conclusion
Above is the tutorial about how to use the range() function in Python through examples.
Thanks for reading!