Section 24.3 Using Random Numbers
If we want to simulate something like flipping a coin, we can assign a different number to each possible outcome. There are two sides to a coin - heads and tails - so let’s call heads 0 and tails 1. If we make a random integer between 0 and 1, we can think of it as representing heads or tails on the coin:
By using the accumulator pattern and a loop, we could repeat a series of flips. Let’s do 100 flips and count up how many heads (0s) we get. Each time through the loop, we will pick a new random number. We will only add to our accumulator numHeads
if the random value is 0.
Try running the program a few times. You usually won’t get exactly 50, but it will usually be pretty close to that number since we flip 100 coins. Determining if this program is working correctly is a bit of a challenge - it would take too long to use Codelens to watch the whole execution. To sanity check it, try the following:
Change the number of iterations of the loop from 100 to 10. That will be a lot easier to deal with.
Uncomment the two print lines that are commented out. The first will print each of the flips. The second will print each one that was determined to be a head and how many we have seen so far.
-
Now you can verify that:
Note 24.3.1.
Remember that while debugging we should simplify things as much as possible and use print statements to “see” what is happening as our code runs.
Mixed up programs
Checkpoint 24.3.2.
The following program should roll 10 dice (that have sides from 1-6). We want to count print the number of dice that show a 6. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly! You will not use all of the blocks.
import random
numSixes = 0
---
for i in range(10):
---
# pick a number from 1-6
die = random.randrange(1, 7)
---
# pick a number from 1-6
die = random.randrange(1, 6) #paired
---
if die == 6:
---
numSixes = numSixes + 1
---
numSixes + 1 #paired
---
print("We got", numSixes, "6's.")
You have attempted
of
activities on this page.