Python comes with a set of functions useful for generating or manipulating random numbers. The randomness in Python is useful for developing different types of games, lotteries, or other applications dependent on random number generation.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Understanding Randomness in Python
Randomness is an essential concept in programming, allowing for unpredictable and non-deterministic behavior. In Python, randomness is commonly achieved using the random module, which provides functions for generating random numbers, selecting random elements, and shuffling sequences.
To work with random numbers, you can use the following functions from the random module:
random(): Returns a random floating-point number between 0 and 1.
randint(a, b): Returns a random integer between the inclusive range of a and b.
uniform(a, b): Returns a random floating-point number between a and b.
Example that demonstrates the usage of randomness in Python
Here’s an example that demonstrates the usage of randomness in Python:
import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
print("Random number:", random_number)
# Generate a random floating-point number between 0 and 1
random_float = random.random()
print("Random float:", random_float)
# Select a random element from a list
fruits = ["apple", "banana", "orange", "kiwi"]
random_fruit = random.choice(fruits)
print("Random fruit:", random_fruit)
# Shuffle the elements in a list
deck_of_cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
random.shuffle(deck_of_cards)
print("Shuffled deck:", deck_of_cards)
In this example, we use random.randint() to generate a random number between 1 and 10, random.random() to generate a random float between 0 and 1, random.choice() to select a random element from a list, and random.shuffle() to shuffle the elements of a list. These functions showcase the randomness capability offered by the random module in Python.
Using the random() Function for Random Numbers Between 0 and 1
The random module in Python comes with functions useful for generating random numbers according to the coder’s requirements. Every time a code is run, the random number generator won’t give different numbers. But the value generated cannot be predicted beforehand.
The random.randint() function is useful for generating a random number within the range specified by the programmer. The function will provide a random number in the form of an integer data type. The random.randit() function is available in the random module, which must be imported for this function to take place.
The code for generating a random integer between 0 to 1 using the random.randit() is as follows:
id="Floating">import random
x= random.randint(0,1)
print(x)
Output:
1
Generating Floating-Point Numbers with random()
The random.random() function of a random module can generate a random float number from the 0.0, 1.0 semi-open range. The syntax for it is as follows:
import random
x = random.random()
# Random float number
for i in range(3):
print(random.random())
Output:
0.5089695129344164
0.07174329054775652
0.7576474741201431
Check out: NumPy in Python
Generating Random Numbers within a Range using range()
The random function in Python can help generate random numbers from a specified range with the following syntax:
#importing "random" for random operations
import random
# using choice() to generate a random number from a
# given list of numbers.
print("A random number from list is : ", end="")
print(random.choice([1, 4, 8, 10, 3]))
# using randrange() to generate in range from 20
# to 50. The last parameter 3 is step size to skip
# three numbers when selecting.
print("A random number from range is : ", end="")
print(random.randrange(20, 50, 3))
Output:
A random number from list is: 4
A random number from range is: 41
Generating Random Numbers with a Normal Distribution using Gauss()
The Gauss () function is useful for drawing random floating points from a Gaussian distribution. The function considers two arguments corresponding to the parameters. These parameters control the size of the distribution, particularly the mean and the standard deviation.
Check out this example to generate 10 random values from a Gaussian distribution with a 0.0 mean and 1.0 deviation.
Syntax:
# generate random Gaussian values
from random import seed
from random import gauss
# seed random number generator
seed(1)
# generate some Gaussian values
for _ in range(10):
value = gauss(0, 1)
print(value)
Outcome:
1.2881847531554629
1.449445608699771
0.06633580893826191
-0.7645436509716318
-1.0921732151041414
0.03133451683171687
-1.022103170010873
-1.4368294451025299
0.19931197648375384
0.13337460465860485
Generating Random Numbers with a Uniform Distribution using uniform()
The random number generator Python also uses the uniform distribution inversion method to deliver outcomes. The syntax for using the rand to get 1000 random numbers via uniform distribution on the interval is as follows:
rng('default') % For reproducibility
u = rand(1000,1);
Seeding and Reproducibility: Controlling Randomness in Python
If you want to make a sequence of random numbers reproducible, you need to set the random number seed generator using the set.seed(). Take a look at the below example:
set.seed(197)
rnorm(n = 10, mean = 0, sd = 1)
## [1] 0.6091700 -1.4391423 2.0703326 0.7089004 0.6455311 0.7290563
## [7] -0.4658103 0.5971364 -0.5135480 -0.1866703
set.seed(197)
rnorm(n = 10, mean = 0, sd = 1)
## [1] 0.6091700 -1.4391423 2.0703326 0.7089004 0.6455311 0.7290563
## [7] -0.4658103 0.5971364 -0.5135480 -0.1866703
This feature is an integral component of reproducible research.
The random number generator in Python can be used with the help of different commands. Knowing the different commands help with utilizing the right one according to code requirements.
FAQs
Can I generate random numbers in Python with specific decimal precision?
In Python, a random float number with a particular number of decimal places can be generated using the random.uniform() function from the random module and the round function.
How can I generate random numbers in Python without replacement?
The randint() and append() functions can be used in Python to generate random numbers without replacement.
Is the random number generator in Python truly random?
If you take into account the scientific sense, most random data generated using Python isn't truly random. Technically, it is pseudorandom, which produces seemingly random but still reproducible data.
Can I generate random numbers in Python based on a given probability distribution?
You can generate random numbers in Python according to a given probability distribution with the help of the choice() method.
How do I ensure that my random number sequences in Python are reproducible?
The use of random seeds can help with the reproducibility of random number sequences in Python.
Are the random number generation functions in Python suitable for large-scale simulations?
Random number generation functions in Python are suitable for large-scale simulations to evaluate the effectiveness of models.
Can I generate random numbers that follow a specific pattern or correlation?
If you want to generate truly random numbers, they must be independent. Following a specific pattern or correlation means they are not totally random.
What are the applications of random number generators in Python?
The applications of random number generators in Python is valuable in the field of gambling, cryptography, computer simulation, and more.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.