Roll as many dice as you like; the program tallies every result and
draws a little bar chart out of # marks. A loop, the
random module, and a first honest taste of
data — generated, counted, and displayed.
The program
import random
count = int(input("How many dice should I roll? "))
tally = [0, 0, 0, 0, 0, 0]
for roll in range(count):
result = random.randint(1, 6)
tally[result - 1] = tally[result - 1] + 1
print()
print("Results of", count, "rolls:")
for face in range(1, 7):
times = tally[face - 1]
print(face, ":", "#" * times, "-", times)Read it before you run it
Predict in writing first — then run the program and grade yourself.
tallyis a list of six counters. Why does the program sayresult - 1— what goes wrong without the- 1?- Predict the exact output for
0dice. (Yes, zero. Trace it.) - Now imagine
600dice. Roughly what should the six bars look like — and what would a wildly uneven chart suggest about the dice?
Make it yours
- One line. Change the
#bar into a character you like better. - A few lines. After the chart, announce which face came up most often — a loop over the tally will find it.
- A real change. Roll two dice each round and tally the sums from 2 to 12. Run it big, look at the shape of the chart, and explain why 7 turns out to be the celebrity.
Curriculum connection
C1.4
determine the appropriate expressions and instructions to use in a programming statement, taking into account the order of operations
Link to original
C2.2
write programs that use and generate data involving various sources and formats
Link to original
C3.1
analyze existing code to understand the components and outcomes of the code
Link to original
C3.4
write programs that make use of external or add-on modules or libraries
Link to original