所以,我刚开始使用Python,但是我尝试在字典中实现函数(有点像C中的函数指针),但是我仍然停留在如何在没有错误的情况下接收函数返回的值上。下面是我代码中的一个小片段:
def main():
numberOfDice = 5
dice = rollDice(numberOfDice) #rolls dice thrice, returns a list of 5 integers
scoreBoard(dice) #displays Yahtzee scoreboard
value = choice(dice) #value = the category choice[1-13]
whichCategory(value)
def whichCategory(category):
board = {
6: numberOfSixes, # I have 1-13 filled, but just for example
12: yahtzee # this is just to save space.
}
board[category]()
def numberOfSixes(theDice):
count = theDice.count(6)
points = count * 6
return points
def yahtzee(theDice):
yahtzee = 0
ones, twos, threes, fours, fives, sixes = countDice(theDice)
# countDice() determines the amount that each number is present in the
# list and then returns those six variables.
if any(x==5 for x in(ones, twos, threes, fours, fives, sixes)):
yahtzee = 50
return yahtzee
在滚动三次并最终确定骰子(整数列表)之后,我从whichCategory()的选项中选择我的值,然后它进行正确的计算,从这些函数中吐出正确的返回值,但是我会得到这样的错误(输入两个6(12分)):
Traceback (most recent call last):
File "C:\python\Lib\idlelib\Yahtzee.py", line 407, in <module>
main() # My call to main()
File "C:\python\Lib\idlelib\Yahtzee.py", line 18, in main
whichCategory(value)
File "C:\python\Lib\idlelib\Yahtzee.py", line 90, in whichCategory
board[category]()
TypeError: yahtzee() missing 1 required positional argument: 'theDice
有趣的是,它说的错误是yahtzee(),而不是6,我相信这是因为它以某种方式得到了12作为答案,并调用了字典中的第12个关键字。否则我会得到这样一个错误:
Traceback (most recent call last):
File "C:\python\Lib\idlelib\Yahtzee.py", line 407, in <module>
main() # My call to main()
File "C:\python\Lib\idlelib\Yahtzee.py", line 18, in main
whichCategory(value)
File "C:\python\Lib\idlelib\Yahtzee.py", line 90, in whichCategory
board[category]()
KeyError: 50
拜托,我已经找过答案了,但还没找到。如果可能的话,我想把字典中函数的值返回main()。任何帮助都将不胜感激
这是未经测试的,但我认为问题是在
board[category]()
行,您调用了一个函数,但没有使用它所需的值。尝试进行这些更改相关问题 更多 >
编程相关推荐