Home>

I'm studying the python3 tutorial, but I don't understand why (3) and (4) are the answers in the example below. I would appreciate it if you could explain.

code
def scope_test ():
    def do_local ():
        spam = "local spam"
    def do_nonlocal ():
        nonlocal spam
        spam = "nonlocal spam"
    def do global ():
       global spam
       spam = "global spam"
    spam = "test spam"
    do_local ()
    print ("After local assingment:", spam)
    do nonlocal ()
    print ("After nonlocal assingment:", spam)
    do_global ()
    print ("After global assignment :, spam)
scope_test ()
print ("In global scope:", spam)

output
After local assingment: test spam ........... (1)
After nonlocal assignment: nonlocal spam .... (2)
After global assignment: nonlocal spam ..... (3)
IN global scope: global spam ............. (4)

(3) Why is it nonlocal? Isn't it global spam because it is redefined as global spam?
(4) I don't understand why it becomes global spam.

  • Answer # 1

    I remember answering the same question before, but I can't find the source.

    The code in this sample is not good.

    Within a python function, the declared (= assigned) variable is local = valid only within that function

    For reference only, see the value outside the function. If they are nested, they will reverse the order.

    That is the basic.

    Here, if you use nonlocal, you can change the behavior of 1.

    If it is nonlocal, variables outside the function can be used even in the case of assignment.

    global is

    global will refer to what is declared at the outermost (= usually at the file level)

    about it.

    So, this sample doesn't have global spam, so it's confusing.
    I added spam with global scope and tried to explain it.

    # Add this for clarification
    spam ='global spam' # (1) This is global spam
    def scope_test ():
        def do_local ():
            spam = "local spam" # (2) This is specific to the do_local function
        def do_nonlocal ():
            nonlocal spam # (3) Outside the do_nonlocal function = (5)
            spam = "nonlocal spam" # Here, (5) is rewritten.
        def do global ():
           global spam # (4) Since this is global, (1)
           spam = "global spam" # (1) is rewritten
        spam = "test spam" # (5)
        do_local ()
        print ("After local assingment:", spam) # (5) is displayed.
        do nonlocal ()
        print ("After nonlocal assingment:", spam) # (5) is displayed
        do_global ()
        print ("After global assignment :, spam) # (5) is displayed
    scope_test ()
    print ("In global scope:", spam) # (1) is displayed.
    output
    After local assingment: test spam ........... (1)
    After nonlocal assignment: nonlocal spam .... (2)
    After global assignment: nonlocal spam ..... (3)
    IN global scope: global spam ............. (4)