I'm a bit stuck on a homework question that simulates rolling dice. The question asks to create a function that returns a random integer value from 1 to 6, and to create a main program that asks the user how many dice to roll(must be limited to 5 dice), and calls the function to print the generated values. So far I have this:
import random
def dice(number_of_dice):
for i in range(0,number_of_dice):
return random.randint(1,6)
number_of_dice = input("How many dice would you like to roll? ")
while number_of_dice >5:
number_of_dice = input("You may only have a limit of 5 dice, enter a number under 5. " )
print dice(number_of_dice)
When running the program, it only returns one random integer value no matter what the "number_of_dice" input is. What exactly is wrong here?
Any help is appreciated, thanks.
now you can access dice like a list ...
As soon as your
dice
function executes and encounters thereturn
statement for the first time, it returns without continuing the rest of thefor
loop.To fix this, you can declare a local variable inside
dice
that holds the multiple results you want to return. Use statements like(I'll leave it to you to fill in the blanks.)
A more advanced use of Python involves using the
yield
statement to return a single value from a special kind of function called a generator, which remembers where it was and can be restarted later. However, it's worthwhile to get a firm grasp on the basics before using features likeyield
.You use a while loop like this
for the d in the 2d6 etc