Python random randrange() Method
The Python random randrange() method returns a random number from the specified set of increasing bases, with a default value of 1.
Python random randrange() Syntax
The following is the syntax of the randrange() method:
import random
random.randrange ([start,] stop [,step])
Note: randrange() is not directly accessible, you need to import the random module and then call the method via the random static object.
Python random randrange() Parameters
- start : The start value of the specified range, included in the range.
- stop : Specify the end value of the range, not included in the range.
- step : Specify the incremental base.
Python random randrange() Return Value
Returns a random term from the given range.
Python random randrange() Example#1
The following shows an example of using the randrange() method.
#!/usr/bin/python3
import random
# Select an odd number from 1-500
print ("randrange(1,500, 2) : ", random.randrange(1, 500, 2))
# Pick a random number from 0-999
print ("randrange(100) : ", random.randrange(1000))
Output:
Python random randrange() Example#2
The sample code demonstrates that randrange() throws a ValueError, Float value exception. The example uses randrange() to generate an exception for numbers between 14.5 and 100.
#!/usr/bin/python3
import random
print ("Random number from 14.5-100 is : ",end="")
print (random.randrange(14.5,100))
Output:
Python random randrange() Example#3
The sample code demonstrates randrange() exception occurs start >= start, using randrange() to generate numbers between 5000-1000 will raise an exception.
#!/usr/bin/python3
import random
print ("Random number from 5000-1000 is : ",end="")
print (random.randrange(5000,1000))
Output: