Psuedo-random numbers are generated from mathematical calculations that simulate random number generation, but is actually completely deterministic (not random at all). This is the kind of random number generation we will get from the random module. These random numbers can also be duplicated by using the same random seed. This is good for testing, but bad for other applications like cryptography.
"True" random numbers often rely on physical processes connected to hardware to determine random numbers.
random.randint(a, b) pick a random integer from a to b (both inclusive)
random.random() pick a random float from 0 (inclusive) to 1 (exclusive)
random.uniform(a, b) pick a random float
random.choice(list) pick a random element from the list
Here are examples of each:
random.randint(3, 7) could return 3, 4, 5, 6, or 7
random.random() could return .0827192637, .928472617283, etc.
random.uniform(3.4, 7.8) could return 3.987263618, 6.18273829198, etc.
random.choice(["red", "green", "blue"]) could return either "red", "green", or "blue"
It can be very helpful to simulate whether or not an event happens with a certain probability.
random.random() < prob This condition represents whether a random event with probability prob has occurred.
For example, if there's a 25% chance that something happens, the code might look like this:
if random.random() < .25:
#something happens
Sometimes you need to simulate an event with more than 2 possibilities. To do this, you have to use the cumulative probability (add up all the probability of the other evens before it.)
Suppose you want to simulate a spinner with the following probabilities:
20% green
30% blue
25% purple
10% red
15% yellow
You could simulate it like this:
if random.random() < .20:
color = "green"
elif random.random() < .50: 20% + 30% = 50%
color = "blue"
elif random.random() < .75: 20% + 30% +25% = 75%
color = "purple"
elif random.random() < .85: 20% + 30% + 25% + 10% = 85%
color = "red"
else:
color = "yellow"