Python range function

The python range function
In this tutorial, we will discuss Python’s range() function. The Range() function is a native python object that returns a Range object. It is an object that returns a sequence of integers. That is to say that the function generates integers that are between the value given at the start and the stop value, which allows to go through the loop and cause it to stop.
Here is an example of the use of the range() function:
print("Range function : Example to print numbers from range 0 to 4")
for i in range(5):
print(i)
Result :
Range function : Example to print numbers from range 0 to 4 The number is : 0 The number is : 1 The number is : 2 The number is : 3 The number is : 4
The last number obtained in the result is the value 4. In Effect in the range function, the first number starts at 0.
Python range() function syntax
range (start, stop, step)
- The “start” argument of the range() function allows us to specify from which value we want to start the loop on integers ( It’s an optional argument which is equal to 0 by default when the value is not filled)
- The “end” argument of the range() function is the stop value, the function will generate values up to this argument. We are obliged to give this argument, it is the condition of termination of the function.
- The “step” argument is the difference between each step in the result. By default, its value is equal to 1 if it is not given in the function
Some details about the range() function :
- The range() function only works with integers.
- All arguments must be integers (no float, no string).
- All three arguments of the function can be positive or negative.
- The step value must not be zero. Indeed if the step argument is equal to 0, the end value will never be reached and this generates an exception Value error
Python range() function Examples
I am going to show you the 3 possible cases of the range() function according to the different types of arguments filled in :
Example one – Using only one argument in range()
print("Print first 3 numbers - Only end argument")
for i in range(3):
print(i)
Result :
Print first 3 numbers - Only end argument 0 1 2
Example Two – using two arguments in range()
print("Print with 2 arguments : start and end")
for i in range(3, 7):
print(i)
Example Three – Using all arguments in range()
print("All arguments with step = -1")
for i in range(10, 0, -1):
print(i)
Leave a comment if you have a suggestion for this article ! 🙂
If you are interested in python , you can consult this section : https://amiradata.com/category/learning/python/
Comments
Leave a comment