我试图限制一个人在猜测随机数时的尝试次数。当我运行程序时,我得到了这个错误代码,但我不知道下一步该怎么做。你知道吗
Traceback (most recent call last):
File "C:/Python27/coding/Guess.py", line 34, in <module>
main()
File "C:/Python27/coding/Guess.py", line 24, in main
trys(userGuess)
File "C:/Python27/coding/Guess.py", line 29, in trys
trysLeft -= 1
UnboundLocalError: local variable 'trysLeft' referenced before assignment
代码:
import random
def main():
print "Guess a number between 1 and 100."
randomNumber = random.randint(1,100)
found = False
trysLeft = 5
while not found:
userGuess = input("Your guess: ")
if userGuess == randomNumber:
print "You got it!"
found = True
elif userGuess > randomNumber:
trys()
print "Guess lower!"
else:
trys()
print "Guess higher!"
def trys():
trysLeft -= 1
print "You have %d trys left." %trysLeft
if __name__ == "__main__":
main()
有3个选项可以解决此问题:
问题是您在函数中分配trysLeft,因此它假定它具有局部(而不是全局)作用域。但实际上您需要分配全局变量,因此需要声明trysLeft具有全局作用域。将
trys()
函数更改为:有关更多信息,请参见FAQ
FWIW,解决这个问题的正确方法是将变量传递给函数,而不是使用全局变量,但这超出了问题的范围。你知道吗
您需要将
trysLeft
传递给函数,它才能看到它。。。你知道吗当你打电话给
trys
。。。你知道吗相关问题 更多 >
编程相关推荐