Home / Python / Example programs / Useful mini-programs

Python program: Simulate rolling dice

Roll two dice many times and see how often each total appears.

The code

import random
from collections import Counter

random.seed(1)
rolls = [random.randint(1, 6) + random.randint(1, 6) for _ in range(36_000)]
counts = Counter(rolls)
for total in range(2, 13):
    share = counts[total] / len(rolls)
    print(f"{total:>2} {share:5.1%} " + "#" * round(share * 200))

Output

 2  2.8% ######
 3  5.5% ###########
 4  8.5% #################
 5 11.0% ######################
 6 13.9% ############################
 7 16.8% ##################################
 8 13.7% ###########################
 9 11.2% ######################
10  8.5% #################
11  5.6% ###########
12  2.6% #####

How it works

A simulation answers a probability question by trying it many times. 7 is the most common total because more dice pairs add up to it (6 of the 36). The seed makes the result repeatable.

Python features used

Learn the ideas behind it in the free lesson Modules & the Standard Library.