我有点不理解为什么有些变量是局部的,有些是全局的。例如,当我尝试这样做:
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()
I get this error:
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子句让它继续执行(否则它甚至不会进入子句)。令人困惑的是为什么它不给我questions,choices和answers相同的错误提示。当我取消注释这两行时,脚本完美地工作了--即使我没有将问题、答案和选项定义为全局变量。为什么会这样呢?这是我从搜索其他问题中没有能够发现的一个问题--在这里,Python似乎表现得不一致。这是否与我使用列表作为其他变量有关?为什么呢?
(此外,第一次发布者;非常感谢所有提供帮助的人。)
global
:赋值操作不会使变量“非全局”,而是用新的绑定覆盖了全局变量。 - user166390