What are the generations in range function in Python?



In this article , we will learn about how to use Python's range() function with the help of different examples.Python build-in function range() generates the integer numbers from start integer to end integer.example-return range object.
we can iterate over a sequence of numbers produced by the range() function.



range() is a built-in function of Python.it is used when a user needs to perform an action for a specific number of times.
range() use in Python 3 but in Python 2 version use xrange() function.
The range() function is used to generate a sequence of numbers. 


generator object that can be  used to display numbers only by looping.Only particular range is displayed on demand and hence called "Lazy evaluation".

 Now, let's see how to use range() function of Python 3 with the simple example :-

print("Python range() example.......")
print("Get the numbers between range 0 to 10")

in range(10):
          print("numbers : ", i)

Output:-

Python range() example.......
Get the numbers between range 0 to 10
0, 1, 2, 3, 4, 5, 6, 7, 8, 9



Syntax:

range (start, stop[, step])




range() takes three arguments. i.e. start and step are the optional arguments.


  1. 1. A start argument is a starting number of the sequence . i.e., lower  limit. By default, it starts with 0 if not specified.
  2. 2. A stop  argument is an upper limit. i.e. , generate numbers uo to this number, The range() function does not include this number in the result.
  3. 3. The step is a difference between each number in the result,The default value of the step is 1 if not specified.

Example we using two arguments(start, stop) in range() :-


print("Print integers within given start and stop numbers using range() function")

for i in range(5, 10): 
           print(i, end='  ')

Output :-

Print integers within given start and stop numbers using range() function
5, 6, 7, 8, 9



Only two arguments (the start and stop) are passed to the range() function.So by default, t took step value as 1.

Example - using all three arguments in range() function :-

print("Using start, stop, and step arguments in Python range() function")

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

output :-

Using start, stop, and stop arguments in Python range() function
1, 3, 5, 7, 9

All three arguments are specified i.e. start=1, stop=10,step=2.The step value is 2 so the difference between each number is 2.


Points to remember about Python range()  function arguments


  • range() function works only with the integers not string. All arguments must be integers.You can not pass a string or float numbers  or any other type in a start, stop and step argument of a range().
  • All three arguments can be positive or negative.
  • The step value must not be zero.if a step is zero Python raises a ValueError expection.















Reactions

Post a Comment

0 Comments