Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)
AIM
To write a Python program that generates random numbers between 1 and 6 to simulate a dice roll.
ALGORITHM
- Import the random module.
- Create a function to simulate dice roll using random.randint(1, 6).
- Display the menu options to the user.
- Get user choice for single roll, multiple rolls, or exit.
- For single roll, generate and display one random number.
- For multiple rolls, ask for number of rolls and generate that many numbers.
- Display the results with appropriate formatting.
- Continue until user chooses to exit.
PROGRAM
import random
def roll_dice():
"""Function to simulate a single dice roll"""
return random.randint(1, 6)
def display_dice(number):
"""Function to display dice in a visual format"""
dice_faces = {
1: ["┌─────────┐",
"│ │",
"│ ● │",
"│ │",
"└─────────┘"],
2: ["��─────────┐",
"│ ● │",
"│ │",
"│ ● │",
"└─────────┘"],
3: ["┌─────────┐",
"│ ● │",
"│ ● │",
"│ ● │",
"└─────────┘"],
4: ["┌─────────┐",
"│ ● ● │",
"│ │",
"│ ● ● │",
"└─────────┘"],
5: ["┌─────────┐",
"│ ● ● │",
"│ ● │",
"│ ● ● │",
"└─────────┘"],
6: ["┌─────────┐",
"│ ● ● │",
"│ ● ● │",
"│ ● ● │",
"└─────────┘"]
}
for line in dice_faces[number]:
print(line)
# Main program
print("🎲 DICE SIMULATOR 🎲")
print("=" * 30)
while True:
print("\n1. Roll dice once")
print("2. Roll dice multiple times")
print("3. Roll two dice")
print("4. Exit")
choice = input("\nEnter your choice (1-4): ")
if choice == '1':
result = roll_dice()
print(f"\n🎲 You rolled: {result}")
display_dice(result)
elif choice == '2':
try:
num_rolls = int(input("How many times do you want to roll the dice? "))
if num_rolls <= 0:
print("Please enter a positive number!")
continue
print(f"\n🎲 Rolling dice {num_rolls} times:")
results = []
for i in range(num_rolls):
roll = roll_dice()
results.append(roll)
print(f"Roll {i+1}: {roll}")
print(f"\nSummary:")
print(f"Total rolls: {len(results)}")
print(f"Results: {results}")
print(f"Sum: {sum(results)}")
print(f"Average: {sum(results)/len(results):.2f}")
except ValueError:
print("Please enter a valid number!")
elif choice == '3':
dice1 = roll_dice()
dice2 = roll_dice()
total = dice1 + dice2
print(f"\n🎲 First dice: {dice1}")
display_dice(dice1)
print(f"\n🎲 Second dice: {dice2}")
display_dice(dice2)
print(f"\n🎯 Total: {total}")
elif choice == '4':
print("\n👋 Thanks for playing! Goodbye!")
break
else:
print("❌ Invalid choice! Please enter 1, 2, 3, or 4.")
print("\nProgram ended.")OUTPUT
🎲 DICE SIMULATOR 🎲
==============================
1. Roll dice once
2. Roll dice multiple times
3. Roll two dice
4. Exit
Enter your choice (1-4): 1
🎲 You rolled: 4
┌─────────┐
│ ● ● │
│ │
│ ● ● │
└─────────┘
Enter your choice (1-4): 2
How many times do you want to roll the dice? 5
🎲 Rolling dice 5 times:
Roll 1: 3
Roll 2: 6
Roll 3: 1
Roll 4: 5
Roll 5: 2
Summary:
Total rolls: 5
Results: [3, 6, 1, 5, 2]
Sum: 17
Average: 3.40
RESULT
Thus, the given program was successfully executed and the output was verified as per the expected result.
KEY POINTS
- random.randint(1, 6): Generates random integers between 1 and 6 (inclusive)
- Visual Representation: ASCII art used to display dice faces
- Menu-driven: User can choose different rolling options
- Statistics: Program calculates sum and average for multiple rolls
- Error Handling: Validates user input for number of rolls
PROGRAM VARIATIONS
Method 1: Simple Dice Simulator
import random
# Simple dice simulator
def simple_dice():
return random.randint(1, 6)
# Roll dice 10 times
print("Rolling dice 10 times:")
for i in range(10):
result = simple_dice()
print(f"Roll {i+1}: {result}")
# Single roll
print(f"\nSingle roll: {simple_dice()}")Method 2: Using random.choice()
import random
# Using random.choice with list of dice values
dice_values = [1, 2, 3, 4, 5, 6]
def roll_with_choice():
return random.choice(dice_values)
# Roll dice
for i in range(5):
print(f"Roll {i+1}: {roll_with_choice()}")Method 3: Class-based Dice Simulator
import random
class Dice:
def __init__(self):
self.history = []
def roll(self):
result = random.randint(1, 6)
self.history.append(result)
return result
def get_statistics(self):
if not self.history:
return "No rolls yet!"
return {
'total_rolls': len(self.history),
'sum': sum(self.history),
'average': sum(self.history) / len(self.history),
'max': max(self.history),
'min': min(self.history)
}
# Usage
my_dice = Dice()
for i in range(10):
result = my_dice.roll()
print(f"Roll {i+1}: {result}")
print("\nStatistics:", my_dice.get_statistics())COMMON ERRORS & SOLUTIONS
ModuleNotFoundError
Make sure to import the random module at the beginning of your program.
ValueError in input
Use try-except blocks to handle invalid input when asking for number of rolls.
Wrong range in randint()
Remember that randint(1, 6) includes both 1 and 6 in the possible results.
VIVA QUESTIONS
What is the difference between randint() and choice()?
randint(a, b) generates random integers between a and b (inclusive), while choice(seq) selects a random element from a sequence.
How do you ensure truly random results?
Python's random module uses a pseudorandom number generator. For cryptographic purposes, use the secrets module instead.
What does random.seed() do?
random.seed() initializes the random number generator with a specific value, making the sequence reproducible.
How would you simulate rolling two dice simultaneously?
Call randint(1, 6) twice and store the results in separate variables, then add them for the total.
What is the probability of getting each number on a fair dice?
Each number (1-6) has an equal probability of 1/6 or approximately 16.67% on a fair six-sided dice.
How can you test if the dice simulator is fair?
Roll the dice many times (e.g., 10000) and check if each number appears approximately 1/6 of the time.
What other random functions are available in Python?
random.uniform(), random.random(), random.shuffle(), random.sample(), etc. for different random operations.
How would you modify this for a 20-sided dice?
Change randint(1, 6) to randint(1, 20) and update the display function accordingly.
Related Resources
- Python Random Module
- Random Number Generation Tutorial
- Functions in Python
- Python Programming MCQs
- More Random Programs
Need Help?
Join our tuition classes for personalized guidance and doubt clearing sessions.
Register for Classes →