Python 3 – Number randrange() Method
In Python, the randrange()
method is commonly used to generate a random number within a given range. The randrange()
method is part of Python’s random library, which offers multiple functions for generating random numbers.
The randrange()
method is a flexible function that has several optional parameters to customize the number range and spacing. The randrange()
method returns a random integer that is selected from a range of integers.
Syntax
randrange(start, stop, step)
Parameters
start
: The starting point of the range of integers. This value is inclusive.stop
: The stopping point of the range of integers. This value is exclusive.step
: The step size of the range.
If start
is omitted, it defaults to 0. If step
is omitted, it defaults to 1.
Examples
Here are a few examples of how to use the randrange()
method:
Example 1: Generate a random number between 0 and 9
import random
random_number = random.randrange(10)
print(random_number)
Output:
7
Example 2: Generate a random number between 1 and 10, in steps of 2
import random
random_number = random.randrange(1,11,2)
print(random_number)
Output:
5
Example 3: Generate a random number between 10 and 50
import random
random_number = random.randrange(10,51)
print(random_number)
Output:
20
Example 4: Generate a random number between -50 and -10
import random
random_number = random.randrange(-50,-9)
print(random_number)
Output:
-47
Important Considerations
- When using the
randrange()
method, the stop value is exclusive. This means that the highest possible value that can be returned is one less than the stop value. - If you provide a step value that is greater than the range of integers you are selecting from, the
randrange()
method will not return any integers.
Conclusion
The randrange()
method is a useful tool for generating random numbers in Python. With a range of customization options, it can be tailored to fit specific use cases. By efficiently selecting random numbers from a range, randrange()
can be a powerful function for a variety of applications.