我有一點麻煩理解爲什麼有些變量是局部的,有些是全球性的。例如。當我試試這個:爲什麼一些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似乎並不一致。它是否與我使用列表作爲其他變量?這是爲什麼?
(另外,第一次海報,非常感謝所有我發現雖然有幫助,不需要發問。)
分配的方法*總是*創建一個[新]本地綁定,除非該變量是'global''ed:轉讓不會使變量「非全局」,而是與陰影一個新的綁定全局變量。 – 2012-11-13 03:10:32