There are several functions in Python that provide the ability to generate random numbers. All of these functions are present in the
random module which can be imported using
The three primary functions used for random number generation are:
This function returns a random floating point value between
import random # A number between 0 and 1 num = random.random() print num # A number between 0 and 100 num = random.random() * 100 print num # A number between -50 and 50 num = random.random() * 100 - 50 print num
randint function takes in a range and produces an integer between that range.
import random # A random integer between 1 and 40 num = random.randint(1, 40) print num
Just as the
randint function generates an integer within a given range,
uniform does the same for floating point numbers.
import random # A floating point number between 1 and 50 num = random.uniform(1, 50) print num
View all Courses