碰巧的是,我刚刚开始使用Python编程,而我正要编写一个小剪刀石头布的游戏。
不幸的是,当我尝试运行脚本时,出现以下错误:
file rps.py, line 53 in game
compare (move,choice)
NameError: name 'move' is not defined"
到目前为止,这是我的代码:
from random import randint
possibilities = ['rock', 'paper', 'scissors']
def CPU(list):
i = randint(0, len(list)-1)
move = list[i]
#print (str(move))
return move
def User():
choice = str(input('Your choice? (Rock [r], Paper[p], Scissors[s])'))
choice = choice.lower()
if choice == 'rock' or choice == 'r':
choice = 'rock'
elif choice == 'scissors' or choice =='s':
choice = 'scissors'
elif choice == 'paper' or choice == 'p':
choice = 'paper'
#print ('Your choice: ' + str(choice))
return choice
def compare(c, u):
if c == u:
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('That is what we call a tie. Nobody wins.')
elif c == 'paper' and u == 'rock':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you, my friend, lose.')
elif c == 'paper' and u == 'scissors':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
elif cc == 'rock' and u == 'paper':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
elif c == 'rock' and u == 'scissors':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you lose.')
elif c == 'scissors' and u == 'paper':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you lose.')
elif c == 'scissors' and u == 'rock':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
def game():
CPU(possibilities)
User()
compare(move, choice)
game()
我很确定在定义函数compare(c,u)
并在括号中添加参数“ c”和“ u”时,我做错了什么。我以为自己可以通过使用return语句来确保可以使用这些变量。
我一般对编程还是比较陌生的,因此没有经验,所以请客气!
问题在于您仅在调用函数CPU
,User
而没有将它们分配给任何变量。因此,你需要重新定义你的函数game
,如
def game():
move = CPU(possibilities)
choice = User()
compare(move, choice)
这样,您将在调用其他两个函数之后使用edcompare
值的本地副本来return
调用该函数。
您可以return
通过参考官方文档来了解有关函数和声明的更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句