When creating a simulation, we need a way to simulate unpredictable events. Is the driver of a car going to choose to turn at a certain intersection? What will the weather be like in an hour? We may have some idea of what answers are reasonable for these questions, and how likely each answer is, but at some point, we will have to resort to trying to pick an answer randomly while obeying what we believe the odds of different outcomes are.
In Python, to generate random values, we use the
random
library. To pick a random integer, we use the
randrange
function in the
random
library. To use it, we have to import the library, and then call the function. Try running this program a few times to see that it does in fact generate a random number each time it runs:
As shown above, the
randrange
function can be called with a starting value (inclusive) and the ending value for the range (exclusive). So
randrange(1, 5)
picks an integer from the range that starts at 1 and ends before 5. We can also call it with just an end value like
randrange(5)
Note 24.2.3.
Computers can’t usually generate truly random numbers without measuring something that is random (like static noise on radio frequencies). If they don’t have access to something like that, they must rely on generating
pseudorandom numbers - numbers that look random even though they are created using some mathematical recipe. Python takes the system time as a starting point (since it is always changing) and then uses a mathematical recipe to “pick” the next random number each time we ask for one.
When these
pseudorandom generators aren’t coded well, they can cause issues with simulations or cryptography that rely on their results.