碰巧我正在使用Python进行编程,我正准备编写一个小石头剪刀游戏.
不幸的是,当我尝试运行我的脚本时,我收到以下错误:
file rps.py, line 53 in game
compare (move,choice)
NameError: name 'move' is not defined"
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
当我定义函数compare(c,u)并在括号中添加参数'c'和'u' 时,我很确定我做错了.我以为我确保通过使用之前的return语句能够使用这些变量.
我对编程很新,因此缺乏经验,所以请善待!
问题是你只是调用函数CPU,User但你没有将它们分配给任何变量.因此,你需要重新定义你的函数game,如
def game():
move = CPU(possibilities)
choice = User()
compare(move, choice)
Run Code Online (Sandbox Code Playgroud)
这样compare,return在调用其他两个函数后,您将使用值的本地副本调用该函数.
您可以参考return官方文档来参考有关函数和语句的更多信息