UnboundLocalError when manipulating variables yields inconsistent behavior

后端 未结 3 2025
别跟我提以往
别跟我提以往 2021-01-23 03:27

In Python, the following code works:

a = 1
b = 2

def test():
    print a, b

test()

And the following code works:

a = 1
b = 2
         


        
3条回答
  •  情书的邮戳
    2021-01-23 04:13

    Let me give you the link to the docs where it is clearly mentioned.

    If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local.

    (emphasis mine)

    Thus your variable a is a local variable and not global. This is because you have a assignment statement,

    a = 3
    

    In the third line of your code. This makes a a local variable. And referring to the local variable before declaration causes an error which is an UnboundLocalError.

    However in your 2nd code block, you do not make any such assignment statements and hence you do not get any such error.

    Another use ful link is this

    Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.

    Thus you are referring to the local variable you create in the next line.

    To prevent this there are two ways

    • Good way - Passing parameters

      Define your function as def test(a): and call it as test(a)

    • Bad way - Using global

      Have a line global a at the top of your function call.

    Python scoping rules are a little tricky! You need to master them to get hold of the language. Check out this

提交回复
热议问题