  Python Number Randrange() Method

Show

Description

The randrange() method in the Python Random module is supposed to return a randomly chosen element from the range(start, stop, step). The randrange() function of Pythonâ€™s random module is used for generating the pseudo-random number amongst the specific range of values. For example, if one wants to generate a random number in between 10 to 50 then you may make use of this function.

Syntax

Here is the syntax for randrange() method:

choice( seq )

Note - One cannot access this function directly, so it is required to import the random module in Python and then we are supposed to call this function making use of the random static object.

Parameters

• start - It indicates the Start point of the range. This shall be included in the range.
• stop - It indicates the Stop point of the range. This shall be excluded from the range.
• step - It indicates the Steps to be added within a number in order to decide a random number.

Return Value

This method is supposed to return a random item from the specified range

Example

The example below shows the usage of the randrange() method.

#!/usr/bin/python
import random

# Select an even number in 100 <= number < 1000
print "randrange(100, 1000, 2) : ", random.randrange(100, 1000, 2)

# Select another number in 100 <= number < 1000
print "randrange(100, 1000, 3) : ", random.randrange(100, 1000, 3)

When we run the above program, it produces the following result:

randrange(100, 1000, 2) :  976
randrange(100, 1000, 3) :  520

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.