ByteBoard Notes Notes

Write a random number generator that simulates a dice

Computer Science XII · Experiment 14 of 29 · Python

★ CBSE suggested12-CSPython programs
Expt. No.14
Page No.28

Dice simulator

Aim

To write a Python program that simulates a dice: each roll gives a random number from 1 to 6.

Concepts used

Algorithm

  1. Define roll_dice() that returns random.randint(1, 6).
  2. Repeat: ask the user to type r to roll or q to quit.
  3. If the user types q, stop; otherwise roll the dice and display the number.

Program

# Dice simulator using the random module import random def roll_dice():    return random.randint(1, 6) while True:    choice = input("Type r to roll the dice or q to quit: ")    if choice == "q":        print("Thanks for playing")        break    print("You rolled:", roll_dice())

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python dice_simulator.py
Type r to roll the dice or q to quit: r You rolled: 4 Type r to roll the dice or q to quit: r You rolled: 1 Type r to roll the dice or q to quit: r You rolled: 1 Type r to roll the dice or q to quit: q Thanks for playing

✓ Printed by running this program, not typed by hand.

Result

Three rolls each displayed a random number from 1 to 6, and typing q ended the program. Your numbers will be different on every run.

Viva voce: what the examiner may ask

01Why is randint(1, 6) correct for a dice but randrange(1, 6) is not?

randint includes both ends (1 to 6); randrange(1, 6) stops before 6, so a six would never appear.

02How does the while True loop end?

The break statement runs when the user types q.

03Why is the random number generated inside a function?

The function can be reused and the code reads more clearly: roll_dice() says what it does.

Variations for the lab test

  1. Roll two dice and display their sum.
  2. Roll the dice 600 times and count how often each face appears.
  3. Keep rolling until a six appears and count the rolls.
! Common mistake Calling random.randint(1, 6) once before the loop and printing that value every time gives the same number on every roll.
Back to the 12-CS index