Home »
Python »
Python Programs
Python program to design a dice throw function
An example of random.choice() in Python: Here, we are going to learn how to design a function that can be used as dice throw and the function will return a random value between 1 to 6?
By Anuj Singh Last updated : January 12, 2024
Problem statement
Write a Python program to design a dice throw function.
Solution overview
Here, we are going to build a dice() function using Python. The program is so simple as an introductory program for defining a function. The function is going to use an inbuilt library naming random. This random library helps us to choose a random value of the variable within the range.
Designing a dice throw function
To design a dice-throw function, use the random.choice() method and pass the list of the numbers between 1 to 6, when the function is called, it will return a random value between 1 to 6 which will be the number of the dice of throwing.
Consider the below statement:
random.choice([1,2,3,4,5,6])
The above function will choose a random value with a probability of 0.167 each i.e. all are independent to each other which will work as dice.
Python program to design a dice throw function
import random
# function definition "dice"
# it will return a random value from 1 to 6
def dice():
return random.choice([1, 2, 3, 4, 5, 6])
# main code
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
print("DICE THREW : ", dice())
Output
The output of the above program is:
RUN 1:
DICE THREW : 5
DICE THREW : 3
DICE THREW : 5
DICE THREW : 4
DICE THREW : 3
DICE THREW : 5
DICE THREW : 3
DICE THREW : 3
DICE THREW : 4
DICE THREW : 6
RUN 2:
DICE THREW : 6
DICE THREW : 5
DICE THREW : 2
DICE THREW : 1
DICE THREW : 4
DICE THREW : 2
DICE THREW : 2
DICE THREW : 1
DICE THREW : 2
DICE THREW : 2
To understand the above program, you should have the basic knowledge of the following Python topics:
Python Basic Programs »