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

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

我收到这个错误:

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 似乎不一致。这与我使用列表作为其他变量有关系吗?这是为什么?

(另外,第一次张贴者;非常感谢我在不需要提问的情况下发现的所有帮助。)

最佳答案

这是因为您要分配给分数questionsanswers 变量只被读取,不被写入。

当你赋值给一个变量时,那个名称具有你所在的当前方法、类等的作用域。当你试图获取一个变量的值时,它首先尝试当前作用域,然后是外部范围,直到找到匹配项。

关于python - 为什么有些 Python 变量保持全局,而有些需要定义为全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355063/

相关文章:

python - 如何从无限生成器列表中获取前 n 个元素?

ruby-on-rails - 如何使类\对象在rails中全局可用?

c - 当有两个具有相同符号但不同类型的全局变量的 .c 文件时,引用如何工作?

python - 如何停止使用 websockets.serve() 创建的 websocket 服务器?

python - Django 模板 : how do I use key to access value?

python - 关联 .csv 列数据以进行计算

python - 池().map : modify the shared object

javascript - 将全局变量抽象为属性?

Android - 使 SoundPool 成为全局类? (适用于所有其他类(class))

c++ - 在确保翻译单元之间的可用性时是否弃用静态?