Die Roller
After Codecademy Loops
Write a program to roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice to roll - and generates random roll values for each die rolled. Print out each roll and then return the string “That’s all!” An example output:
>>>
How many sides are on each die? 6
How many dice are there? 3
4
5
3
...and that's it!
>>>
You can add a total if you want.
>>>
How many sides are on each die? 6
How many dice are there? 3
4
5
3
...and that's it!
>>>
You can add a total if you want.
Hint:
Use a function:
def diceRoller (sides,dice):
#...put your for loop here:
#Call the function using 2 parameters the user chose.
diceRoller(rawinputvariableforsides, rawinputvariablefordice)
for loop
>>> # Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
... print w, len(w)
cat 3
window 6
defenestrate 12
#You are asking how many dice there are. What if there are 100 dice?
for dice in range (numberofdice):
...print(random.randint())
Slides
Use int()
Use randint
Review:
Read about the random module.
import random
random.randint(1, 6)
>>> random.random() # Random float x, 0.0 <= x < 1.0 0.37444887175646646
>>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0 1.1800146073117523
>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included 7
>>> random.randrange(0, 101, 2) # Even integer from 0 to 100 26
>>> random.choice('abcdefghij') # Choose a random element 'c'
def diceRoller (sides,dice):
#...put your for loop here:
#Call the function using 2 parameters the user chose.
diceRoller(rawinputvariableforsides, rawinputvariablefordice)
for loop
- When do I use for loops?
>>> # Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
... print w, len(w)
cat 3
window 6
defenestrate 12
#You are asking how many dice there are. What if there are 100 dice?
for dice in range (numberofdice):
...print(random.randint())
Slides
Use int()
Use randint
Review:
Read about the random module.
import random
random.randint(1, 6)
>>> random.random() # Random float x, 0.0 <= x < 1.0 0.37444887175646646
>>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0 1.1800146073117523
>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included 7
>>> random.randrange(0, 101, 2) # Even integer from 0 to 100 26
>>> random.choice('abcdefghij') # Choose a random element 'c'