0

Why is this not possible?

CONSTANT = 1
def main():
    if False:
        CONSTANT = 0
    print(CONSTANT)
main()

Error:

UnboundLocalError: local variable 'CONSTANT' referenced before assignment

Explicit assignment doesn't change anything:

CONSTANT = 1
def main():
    CONSTANT = CONSTANT
    if False:
        CONSTANT = 0
    print(CONSTANT)
main()

Only changing the name does the job:

CONSTANT = 1
def main():
    constant = CONSTANT
    if False:
        constant = 0
    print(constant)
main()

That's kind of annoying, can I somehow avoid that behaviour?

4

1 回答 1

2

定义CONSTANT为全局。

CONSTANT = 1
def main():
    global CONSTANT
    print(CONSTANT)
    CONSTANT = 0
    print(CONSTANT)
main()
于 2013-09-07T20:16:50.580 回答