2015-09-23 38 views
1

我試圖限制一個人在嘗試猜測隨機數時嘗試的次數。我運行該程序時遇到此錯誤代碼,無法找出下一步該做什麼。如何減少遊戲中剩餘的遊戲數量?

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() 

回答

0

的問題是,你的功能分配trysLeft,則認爲它具有本地(而非全球)範圍。但是您實際上想要分配全局變量,因此您需要聲明trysLeft具有全局範圍。更改trys()功能如下:

def trys(): 
    global trysLeft 
    trysLeft -= 1 
    print "You have %d trys left." %trysLeft 

欲瞭解更多信息,請參閱FAQ

FWIW,解決這將是一個變量傳遞給你的函數,而不是使用全局變量的正確方法,但這是你的問題的範圍之外。

+0

是嚴重阻礙全局。 –

+0

非常感謝,我懂了! –

+0

當然!但是對於學習編程的人來說,它混淆了爲什麼代碼(如寫)不起作用。解釋傳遞參數更好,並不能說明第一種方法不起作用的困惑。 –

-1
def trys(self): 
    self.trysLeft-=1 

應該這樣做!

自我指的是你目前的類的實例。

在Java thisMe在VBA類似。

+0

'self'將在OP是使用一類 – Wondercricket

+0

的確OP不被使用。它被編碼爲意圖是一個類。 –

2

你需要傳遞trysLeft的功能,它看到它......

def trys(trysLeft): 
     trysLeft -= 1 
     print "You have %d trys left." %trysLeft 
     return trysLeft 

,然後當你打電話trys ...

trysLeft = trys(trysLeft) 
3

你有3個選項,以解決這個問題:

  • 把trysLeft放在全局(不是個好主意)
  • 添加功能改掉()到類,並引用其作爲self.trysLeft
  • 傳遞變量到改掉()函數。