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
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
random.randint(1, 6)returns a random whole number from 1 to 6, and unlikerange(), both 1 and 6 are included.- The
forloop rolls the dice five times, andtotaladds up the rolls. - The output changes on every run, because each roll is random.
- In the
input()version from the comment, thewhileloop keeps rolling for as long as the player types y.
Another way to write it
Checking that the dice is fair
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises