Python Miniprojects : Simulation of a dice roll
Dice has 6 faces. Each one has a value. Here, ‘random.randint()’ function is used.
Let us implement this.
- · Simple dice roll
- · Multiple dice roll
- · Using function
- · Object oriented approach
Simple dice roll:
It uses
randint() function to roll a dice with in the range 1 to 6.
Code:
import random
dice_result = random.randint(1, 6)
print(f"The dice rolled: {dice_result}")
Output:
The dice rolled: 6
Multiple dice roll:
This
method gets the input from the user about how many dice to roll. Based on the
input, it rolls the dice and display the input.
Code:
import random
num_dice = int(input("Enter how many number of dice to
roll: "))
for i in range(num_dice):
print(f"Dice {i+1}:
{random.randint(1, 6)}")
Output:
Enter how many number of dice to roll: 5
Dice 1: 2
Dice 2: 3
Dice 3: 1
Dice 4: 5
Dice 5: 2
Using functions:
This method
creates a function to implement the roll a dice. It randomly gives you the
value for dice.
Code:
import random
def roll_dice(sides=6):
return random.randint(1,
sides)
print(f"Rolled a dice using function: The dice value is
{roll_dice()}")
Output:
Rolled a dice using function: The dice value is 3
Object oriented Approach:
This method
uses encapsulation, constructor and function concepts in object oriented methodology.
Code:
import random
class Dice:
def __init__(self,
sides=6):
self.sides = sides
def roll(self):
return random.randint(1,
self.sides)
dice = Dice()
print(f"Dice rolled: The value is {dice.roll()}")
Output:
Dice rolled: The value is 5
These are methods to simulate a dice roll in python. Hope,
you understood the concept. Keep Coding!!!!
Comments
Post a Comment