【发布时间】:2013-11-18 16:02:08
【问题描述】:
我正在尝试创建一个函数来计算一个数字在 5 个随机数的列表中出现的次数,然后在一个新列表中生成它。直到最后,当我想测试它时,它似乎都很好,当我让它打印 countVals 函数时,它说没有定义骰子。我有一个以前的函数,它将骰子定义为 5 个随机数的列表。
def rollDice() :
dice = []
for i in range(5) :
dice.append(random.randint(1,6))
return (dice)
print(rollDice()) #Here is the previous function as requested
def countVals(dice):
present = 0 #present is how many times each number appears in dice
totals = []
for i in range (6):
for j in range(5):
if dice[j] == (j+1) :
present += 1
totals[j] = present
return(totals)
print(countVals(dice)) #getting the following error on this line:
打印(countVals(骰子)) NameError:名称“骰子”未定义
我想我只是脑子一片空白,但我该如何定义骰子?我认为它会在我之前的函数中定义,该函数创建名为 dice 的 5 个数字列表
我是否遗漏了一些重要的骰子应该在主代码中?
【问题讨论】:
-
您遇到什么错误?发布完整的回溯。
-
嗯,你有没有在任何地方定义
dice? -
如果
dice应该是一个列表,你不能将它作为一个函数使用;你会使用dice[j],而不是dice(j)。 -
有关您编写的代码问题的问题必须在问题本身中描述具体问题 - 并包含重现问题的有效代码。有关指导,请参阅 SSCCE.org。
-
没有基本了解
标签: python function python-3.x