Editor

Python Program to Simulate a Dice Roll

Beginner · Games and random numbers · CBSE class 12 practical list

A dice has six faces numbered 1 to 6, and each roll lands on one of them by chance. This program simulates a dice with the random module, which picks a whole number from 1 to 6 with equal chances. The CBSE class 12 practical list asks for it as a random number generator that generates random numbers between 1 and 6.

Program

dice_roll.py
import random
# A real game rolls each time the player says yes:
# while input("Roll the dice? (y/n): ") == "y":
# print("You rolled", random.randint(1, 6))
# Here the dice is rolled 5 times, so the program runs on its own.
total = 0
for turn in range(1, 6):
value = random.randint(1, 6) # a whole number from 1 to 6, both ends included
total += value
print(f"Roll {turn}: you rolled a {value}")
print("Total of 5 rolls:", total)
Output
Roll 1: you rolled a 6
Roll 2: you rolled a 2
Roll 3: you rolled a 4
Roll 4: you rolled a 1
Roll 5: you rolled a 2
Total of 5 rolls: 15

How it works

  1. random.randint(1, 6) returns a random whole number from 1 to 6, and unlike range(), both 1 and 6 are included.
  2. The for loop rolls the dice five times, and total adds up the rolls.
  3. The output changes on every run, because each roll is random.
  4. In the input() version from the comment, the while loop keeps rolling for as long as the player types y.

Another way to write it

Checking that the dice is fair

Checking that the dice is fair
import random
counts = [0, 0, 0, 0, 0, 0, 0] # counts[1] to counts[6] are used
for i in range(6000):
face = random.randint(1, 6)
counts[face] += 1
for face in range(1, 7):
print("Face", face, "came up", counts[face], "times")
Output
Face 1 came up 959 times
Face 2 came up 985 times
Face 3 came up 1048 times
Face 4 came up 1003 times
Face 5 came up 993 times
Face 6 came up 1012 times

Rolled 6000 times, each face comes up close to 1000 times, which shows that every number is equally likely. The exact counts change on every run.

Try it yourself

Roll two dice in each turn and print "Doubles!" when both show the same number.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises