Skip to main content

Welcome to CS

Section24.2Random Numbers

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)

Checkpoint24.2.1.

What is a value that the recipe random.randrange(12, 20) can produce?
• 0
• 12 is the lowest value that will be selected
• 10
• 12 is the lowest value that will be selected
• 19
• Correct.
• 20
• The range is exclusive of the second value. 20 will not be picked

Checkpoint24.2.2.

We want to make a random whole number between 2 and 4. Fill in the blank in this recipe: random.randrange(________________)

Note24.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.
You have attempted of activities on this page.