碰巧我正在使用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语句来使用这些变量。
我对编程很新,因此缺乏经验,所以请善待!
答案 0 :(得分:5)
问题是您只调用函数CPU
和User
,但您没有将它们分配给任何变量。因此,您需要在
game
def game():
move = CPU(possibilities)
choice = User()
compare(move, choice)
这样,在调用其他两个函数后,您将使用值compare
的本地副本调用函数return
。
您可以参考官方documentation
,详细了解功能和return
声明