Rolling a 6, 8, 10 and 12 sided dice.
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
import xIncludes functions from the library ‘x’ in your program. E.g. import random will give you access to use commands in the ‘random’ library. Importing libraries allows you to extend a programming language with new commands that are not already built-in to the language. Libraries are created by programmers for other programmers to use in their programs.
random.seed(x)Sets the seed x to be used by the random number algorithm. The value of x can be omitted to use the current time as the seed number instead. Using the time of day as the seed gives the impression of truly random numbers.
random.randint(x, y)Generates a random number between x and y inclusive.
Questions to think about with this program to check your understanding:
Identify two constants in the program that could be variables instead.
The numbers 1 and 6 could be constants in this version of the program although that would limit the program to only simulating the roll of a six-sided dice.
State what the two parameters are used for in the randint command in line 13.
The lowest and highest number that can be generated by the random number algorithm. Any number between or including these two values could be generated.
Change the program so that it:
Roll a D6
You rolled a 3
Roll a D8
You rolled an 8
Roll a D10
You rolled a 4
Roll a D12
You rolled an 11
# Polyhedral dice program
# -------------------------
# Import libraries
# -------------------------
---
import random
---
# -------------------------
# Subprograms
# -------------------------
# Function to roll a dice.
---
def roll_dice(dice):
---
faces = int(dice)
---
result = random.randint(1, faces)
---
return result
---
# -------------------------
# Main program
# -------------------------
random.seed()
---
dice = input("Roll a D")
---
number = roll_dice(dice)
---
if (number == 8) or (number == 11):
---
print("You rolled an", number)
---
else:
---
print("You rolled a", number)