Class 12 Programs

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

  1. Import the random module.
  2. Create a function to simulate dice roll using random.randint(1, 6).
  3. Display the menu options to the user.
  4. Get user choice for single roll, multiple rolls, or exit.
  5. For single roll, generate and display one random number.
  6. For multiple rolls, ask for number of rolls and generate that many numbers.
  7. Display the results with appropriate formatting.
  8. 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

  1. 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.

  2. How do you ensure truly random results?

    Python's random module uses a pseudorandom number generator. For cryptographic purposes, use the secrets module instead.

  3. What does random.seed() do?

    random.seed() initializes the random number generator with a specific value, making the sequence reproducible.

  4. 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.

  5. 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.

  6. 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.

  7. What other random functions are available in Python?

    random.uniform(), random.random(), random.shuffle(), random.sample(), etc. for different random operations.

  8. 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

Need Help?

Join our tuition classes for personalized guidance and doubt clearing sessions.

Register for Classes →

Practice More

Try similar random number programs to strengthen your concepts.

View All Programs →