To get a random number in Python, use the randint()
function from the random
module.
For example, let’s generate a random integer between 1 and 100:
import random random_number = random.randint(1,100) print(random_number)
Output:
32
To generate a random float, use the uniform function from the random module:
import random random_float = random.uniform(0,100) print(random_float)
Output:
87.95647839475612
These are the two basic use cases you are going to need.
Let’s go through some of the most common questions related to generating random numbers in Python.
How to Generate a Random Float Between 0 and 1
To generate a random float between 0
and 1
, use the uniform()
function from the random
library.
For example:
import random random.uniform(0, 1)
How to Generate a Random Integer Between 0 and 1
To generate a random number that is either 0 or 1, use the randint()
function from the random
library.
For example:
import random random.randint(0, 1)
How to Pick a Random Number from a List of Numbers
To randomly choose a number from a list of numbers, use the choice()
function from the random
module.
For example:
import random numbers = [1, 2, 3, 4, 5] random_selection = random.choice(numbers) print(random_selection)
Output:
4
How to Generate a Random Number Between 1 and 100
To generate a random number between 1 and 100, use the uniform()
function from the random
library like this:
import random random_number = random.randint(1, 100) print(random_number)
Output example:
63
How to Get a Normally Distributed Random Number in Python
To generate a random number from the Gaussian distribution, use the random
library’s gauss()
function.
For example, let’s generate a random number from a normal distribution with the mean of 5
and standard deviation of 10
:
import random # The mean of the distribution mu = 10 # The standard deviation of the distribution sigma = 5 print(random.gauss(mu, sigma))
Output example:
11.2619492713289371
How to Simulate Coin Toss in Python—Heads or Tails
To simulate a coin toss in Python, you need to randomly select between heads and tails.
To do this, create a list that has both heads and tails in it. Then choose one of them randomly using the random.choice()
function.
Here is how it looks in the code:
import random def coinToss(): return random.choice(['Tails', 'Heads']) print(coinToss())
Output example:
Tails
Thanks for reading. Happy coding!