Answer: We can generate random integers using random modules and randint() functions.
The random module helps generate random numbers between a specified range having said ‘Start’ and ‘End’ points. There are plenty of methods to generate random numbers. In this blog, we will see the methods to generate random numbers.
Table of Contents:
Methods to Generate Random Integers between 0 and 9 in Python
Python provides various built-in methods that can be used to generate random integers between a range of specified values. Following are some of these methods explained with the help of examples:
Method 1: Using random module in Python
The random module will help you to generate or create a random number between the two parameters.
1. Using random.systemrandom class in Python
The random.systemrandom class in Python is a part of the random module in which instead of generating random default numbers between two points “Start” and “End,” it will use the operating system’s source of random generation.
Example:
Output:
2. Using the random.uniform() module in Python
The random.uniform() module in Python helps to generate random floating-point values within the specified range.
Example:
Output:
Method 2: Using randint( ) function in Python
The randint( ) function in Python will help you to generate random numbers within the set of two boundaries. It has an upper bound, which is ‘start’, and a lower bound, which is ‘end’.
Example:
Output:
Method 3: Using randrange( ) function in Python
This randrange ( ) function in Python will generate the random numbers in 3 steps:
Step 1: ‘Start’: it will decide the starting range
Step 2: ‘Stop’: This will decide the end of the range
Step 3: ‘Step’: will provide a value between the two ranges; if there is none, then it will provide the default as 1.
Example:
Output:
Method 4: Using secrets.randbelow( ) function in Python
In this method, secrets.randbelow( ) function will generate cryptographically secure random numbers. When the range is decided, only the ‘End’ range will be set, as the method follows the ‘End’ exclusive. It will have all the numbers of n, where all the numbers will be non-negative numbers.
Example:
Output:
Conclusion
In conclusion, when generating random numbers in Python, the random.systemrandom and random.uniform classes offer OS-based randomness for enhanced security. The randint() function generates random integers within a specified inclusive range, while the randrange() function offers more flexibility with optional step values. For cryptographic purposes, the secrets.randbelow() function ensures secure random number generation.