为什么一些Python变量保持全局,而有些需要定义为全局变量 [英] Why some Python variables stay global, while some require definition as global

查看:220
本文介绍了为什么一些Python变量保持全局,而有些需要定义为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解为什么有些变量是局部变量而有些变量是全局变量时遇到了一些麻烦。例如。当我尝试这样:

I'm having a bit of trouble understanding why some variables are local and some are global. E.g. when I try this:

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子句来让它继续前进(否则它甚至不会输入该子句)。令我困惑的是为什么它不会给我提出同样的问题,选择和答案。 当我取消注释这两行时,脚本完美无缺 - 即使没有我将问题,答案和选择定义为全局变量。为什么?这是我无法从搜索其他问题中发现的一件事 - 在这里,Python似乎并不一致。它是否与我使用列表作为其他变量?为什么会这样?

Now, it totally makes sense to me why it's throwing me an error on score. I didn't set it globally (I commented that part out intentionally to show this). And I am specifically not using the while clause to get it to move on (otherwise it won't even enter the clause). What confuses me is why it doesn't give me the same error for questions, choices, and answers. When I uncomment out those two lines, the script works perfectly fine -- even without me defining questions, answers, and choices as global variables. Why is that? This is the one thing I haven't been able to discover from searching other questions -- here it seems that Python is being inconsistent. Does it have to do with me using lists as the other variables? Why is that?

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

(Also, first time poster; thanks so much for all the help I've discovered while haven't needing to ask questions.)

推荐答案

这是因为您将分配给分数问题答案只能被读取,而不能写入。

It's because you're assigning to score. questions and answers are only being read, not written to.

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

When you assign to a variable, that name has the scope of the current method, class, etc. that you are in. When you try to get the value of a variable, it first tries the current scope, and then outer scopes, until it finds a match.

这篇关于为什么一些Python变量保持全局,而有些需要定义为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆