我試圖限制一個人在嘗試猜測隨機數時嘗試的次數。我運行該程序時遇到此錯誤代碼,無法找出下一步該做什麼。如何減少遊戲中剩餘的遊戲數量?
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()
是嚴重阻礙全局。 –
非常感謝,我懂了! –
當然!但是對於學習編程的人來說,它混淆了爲什麼代碼(如寫)不起作用。解釋傳遞參數更好,並不能說明第一種方法不起作用的困惑。 –