Python骰子模拟 [英] Python dice simulation
问题描述
我对模拟掷骰子的家庭作业问题有些困惑.问题要求创建一个返回1到6的随机整数值的函数,并创建一个主程序,询问用户要掷出多少个骰子(必须限制为5个骰子),并调用该函数以打印生成的骰子价值观.到目前为止,我有这个:
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)
在运行程序时,无论"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?
感谢您的帮助.
推荐答案
一旦您的dice
函数第一次执行并遇到return
语句,它就会返回而不会继续执行for
循环的其余部分
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.
要解决此问题,可以在dice
中声明一个局部变量,该变量保存要返回的多个结果.使用类似
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.)
Python的更高级用法包括使用yield
语句从称为 generator 的特殊类型的函数返回单个值,该函数会记住它在哪里,以后可以重新启动.但是,在使用yield
之类的功能之前,有必要牢牢掌握基础知识.
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
.
这篇关于Python骰子模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!