Python dice simulation

2019-03-22 07:57发布

问题:

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.

回答1:

As soon as your dice function executes and encounters the return statement for the first time, it returns without continuing the rest of the for loop.

To fix this, you can declare a local variable inside dice that holds the multiple results you want to return. Use statements like

retval = []

retval.append(...)

return retval

(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 like yield.



回答2:

def dice(number_of_dice):
    for i in range(0,number_of_dice):
        yield random.randint(1,6)  #yield will successivly return as opposed to just return

now you can access dice like a list ...



回答3:

You use a while loop like this

import random

from random import randint

while True:

  dice = input("how many dice would you like to roll?")

    prefix, middle, suffix = dice.partition("d")

for the d in the 2d6 etc

    for _ in range (int(prefix)):

      print (random.randint(1, int(suffix)))