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 import random
.
The three primary functions used for random number generation are:
random()
randint()
uniform
This function returns a random floating point value between 0
and 1
.
import random# A number between 0 and 1num = random.random()print num# A number between 0 and 100num = random.random() * 100print num# A number between -50 and 50num = random.random() * 100 - 50print num
The randint
function takes in a range and produces an integer between that range.
import random# A random integer between 1 and 40num = 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 50num = random.uniform(1, 50)print num
Free Resources