PythonMastery

Dice roller in Python

Roll any number of dice with random.randint and add up the total. Then roll 6000 times and count how often each face appears.

random.randint(1, 6) gives a whole number from 1 to 6, like one throw of a normal die. Call it once for each die and add the results.

The program

python
import random

random.seed(12)  # fixed seed so the output matches this page; remove it for real use


def roll_dice(count, sides=6):
    return [random.randint(1, sides) for _ in range(count)]


count = int(input("How many dice? "))
rolls = roll_dice(count)
print("You rolled:", rolls)
print("Total:", sum(rolls))

Typed in this example: 3. Press Run to type your own.

output
How many dice? 3
You rolled: [4, 3, 6]
Total: 13

How it works

Counting each face over many rolls

With a fair die, each face should come up about one time in six. Roll 6000 times and count:

python
import random

random.seed(12)  # fixed seed so the output matches this page; remove it for real use

rolls = 6000
counts = {face: 0 for face in range(1, 7)}

for _ in range(rolls):
    face = random.randint(1, 6)
    counts[face] += 1

for face, n in counts.items():
    percent = n / rolls * 100
    print(f"{face}: {n:4} ({percent:.1f}%)")
output
1:  994 (16.6%)
2: 1016 (16.9%)
3: 1037 (17.3%)
4:  982 (16.4%)
5:  992 (16.5%)
6:  979 (16.3%)

Each count is close to 1000 (16.7%), but not exactly 1000. Random results always vary a little. The more rolls you make, the closer the percentages get to 16.7%.

The dictionary starts with every face at 0. Without that, counts[face] += 1 would raise a KeyError the first time a face appears. The frequency table program shows other ways to count.

Two dice: why 7 comes up most

When you add two dice, the totals are not equally likely. There are six ways to make 7 (1+6, 2+5, 3+4, 4+3, 5+2, 6+1), but only one way to make 2 or 12:

python
import random

random.seed(12)  # fixed seed so the output matches this page; remove it for real use

counts = {total: 0 for total in range(2, 13)}
for _ in range(3600):
    counts[random.randint(1, 6) + random.randint(1, 6)] += 1

for total, n in counts.items():
    print(f"{total:2} {'#' * (n // 20)}")
output
 2 ####
 3 ##########
 4 ################
 5 ##################
 6 ########################
 7 #############################
 8 #########################
 9 #####################
10 ################
11 #########
12 ####

Each # stands for 20 rolls. The bars rise to a peak at 7 and fall again.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Dictionaries, Modules & Imports