2012-11-13 19 views
4

我有一點麻煩理解爲什麼有些變量是局部的,有些是全球性的。例如。當我試試這個:爲什麼一些Python變量停留全球性的,而有些需要定義全球

from random import randint 

score = 0 

choice_index_map = {"a": 0, "b": 1, "c": 2, "d": 3} 

questions = [ 
    "What is the answer for this sample question?", 
    "Answers where 1 is a, 2 is b, etc.", 
    "Another sample question; answer is d." 
] 

choices = [ 
    ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"], 
    ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"], 
    ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"] 
] 

answers = [ 
    "a", 
    "b", 
    "d" 
] 

assert len(questions) == len(choices), "You haven't properly set up your question-choices." 
assert len(questions) == len(answers), "You haven't properly set up your question-answers." 

def askQ(): 
    # global score 
    # while score < 3: 
     question = randint(0, len(questions) - 1) 

     print questions[question] 
     for i in xrange(0, 4): 
      print choices[question][i] 
     response = raw_input("> ") 

     if response == answers[question]: 
      score += 1 
      print "That's correct, the answer is %s." % choices[question][choice_index_map[response]] 
      # e.g. choices[1][2] 
     else: 
      score -= 1 
      print "No, I'm sorry -- the answer is %s." % choices[question][choice_index_map[answers[question]]] 
     print score 

askQ() 

我得到這個錯誤:

Macintosh-346:gameAttempt Prasanna$ python qex.py 
Answers where 1 is a, 2 is b, etc. 
a) choice 1 
b) choice 2 
c) choice 3 
d) choice 4 
> b 
Traceback (most recent call last): 
    File "qex.py", line 47, in <module> 
    askQ() 
    File "qex.py", line 39, in askQ 
    score += 1 
UnboundLocalError: local variable 'score' referenced before assignment 

現在,它完全是有道理的我,爲什麼它拋出我一個錯誤的分數。我沒有在全球範圍內設置它(我有意將這部分內容表明出來)。而且我特別不使用while子句來讓它繼續前進(否則它甚至不會輸入該子句)。令我困惑的是爲什麼它不會給我提出同樣的問題,選擇和答案。 當我取消註釋這兩行時,腳本完美無缺 - 即使沒有我將問題,答案和選項定義爲全局變量。這是爲什麼?這是我無法從搜索其他問題中發現的一件事 - 在這裏,Python似乎並不一致。它是否與我使用列表作爲其他變量?這是爲什麼?

(另外,第一次海報,非常感謝所有我發現雖然有幫助,不需要發問。)

+2

分配的方法*總是*創建一個[新]本地綁定,除非該變量是'global''ed:轉讓不會使變量「非全局」,而是與陰影一個新的綁定全局變量。 – 2012-11-13 03:10:32

回答

4

這是因爲你分配給scorequestionsanswers只能被讀取,不能寫入。

當您分配給變量時,該名稱具有您所在的當前方法,類等的範圍。當您嘗試獲取變量的值時,它首先嚐試當前範圍,然後外部範圍,直到找到匹配。

+0

這太好了。感謝您的迴應!完全合理。 – pswaminathan

2

這非常有意義,如果你認爲全球是一個解析器指令

當你在做

​​3210

被翻譯成

score = score + 1 

當解析器到達「得分='它會導致解釋器不在本地空間之外進行搜索。

http://docs.python.org/2/reference/simple_stmts.html#global

+0

這確實有道理。我曾經想過,當一個變量被定義在一個高於我所使用的變量的塊中時,該變量上的所有操作都被保留在其範圍內。儘管如此,感謝您鏈接這一點。這有助於我的理解,即分配遵循與閱讀不同的過程。 – pswaminathan

1

會發生什麼事是,Python會在局部範圍內檢查您的變量它會檢查全局範圍之前。所以,當談到questionsanswers,它們永遠不會在局部範圍內設置,所以Python就移動到全球範圍內,在那裏他們被發現。但對於score,Python看到你在做對本地範圍的分配(score += 1score -= 1)和鎖。但是當你在這些語句中提到score時,它還不存在,所以Python會引發異常。

+0

這太好了。感謝您的迴應!完全合理。 – pswaminathan