为什么有些Python变量保持全局,而有些则需要定义为全局变量

psw*_*han 5 python global-variables

我在理解为什么有些变量是局部的并且有些变量是全局变量时遇到了一些麻烦.例如,当我尝试这个:

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()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

现在,我完全有理由为什么它会给我一个错误的分数.我没有在全球范围内设置它(我评论说这部分故意用来表明这一点).而且我特别没有使用while子句让它继续前进(否则它甚至不会进入该子句).令我感到困惑的是,为什么它不会在问题,选择和答案方面给出同样的错误.当我取消注释这两行时,脚本运行得非常好 - 即使没有我将问题,答案和选择定义为全局变量.这是为什么?这是我从搜索其他问题时未能发现的一件事 - 这里似乎Python不一致.是否与我使用列表作为其他变量有关?这是为什么?

(另外,第一次发布海报;非常感谢我发现的所有帮助,而不需要提问.)

Jon*_*art 5

这是因为你要分配给score.在questionsanswers变量仅被读取,不能写入.

分配给变量时,该名称具有您所在的当前方法,类等的范围.当您尝试获取变量的值时,它首先尝试当前范围,然后尝试外部范围,直到它找到了匹配.