Back

Dice - Answers

Q1. Get the code working:

import random

total = 0
for number in range(3):
    roll = random.randrange(1,7)
    print(roll)
    total = total + roll

print('The total of rolling the dice 3 times is',total)

Q2. The code imports the random module. It initialises total to zero. Then it rolls a 6-sided dice three times, each time printing out the dice roll. It keeps a running total and then prints this out at the end of the program.
Q3. To modify the code so that you ask the user how many times they want to roll the dice and then use that number, do this:

import random

times = int(input('How many times do you want to roll the dice >>> '))
total = 0
for number in range(times):
    roll = random.randrange(1,7)
    print(roll)
    total = total + roll

print('The total of rolling the dice',times,'times is',total)

Q4. To modify the code to use a 20-sided dice, do this:

import random

times = int(input('How many times do you want to roll the dice >>> '))
total = 0
for number in range(times):
    roll = random.randrange(1,21)
    print(roll)
    total = total + roll

print('The total of rolling the dice',times,'times is',total)

Q5. Test your code. Remember! Just because you get an output doesn't mean all of the numbers add up correctly. Write down some test data, then predict the result on paper and only then run the code. Finally, compare your prediction with your actual results.
Q6 and Q7. To modify your program so that a single 6-sided dice roll is in a function and is called twice, do this:. 

import random

def diceroll():
    roll = random.randrange(1,7)
    return roll

total = 0
for number in range(2):
    roll = random.randrange(1,7)
    print(roll)
    total = total + roll

print('The total of rolling the dice twice is',total)

Q8, Q9 and Q10.

import random #This imports the random module.

def diceroll():
    '''
    This function simulates the rolling of a single 6-sided dice.
    It requires no arguments to work and returns 1 integer between 1 and 6.
    '''
    roll = random.randrange(1,7)
    return roll #return the result of rolling the dice.

total = 0 #initialise total
for number in range(3):
    roll = random.randrange(1,7)
    print(roll)
    total = total + roll #Keep a running total.

print('The total of rolling the dice three times is',total)

Back