'What is the difference between non local variable and global variable?

I am learning the concepts of programming languages.

I found the terminology "nonlocal" in python syntax.

What is the meaning of nonlocal in python??



Solution 1:[1]

The nonlocal variables are present in a nested loop. A keyword nonlocal is used and the value from the nearest enclosing loop is taken. An example is as:-

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)

The output will be "nonlocal" both the times as the value of x has been changed by the inner function.

Solution 2:[2]

From the documentation about nonlocal statements:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a nonlocal statement, unlike to those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

Names listed in a nonlocal statement must not collide with pre- existing bindings in the local scope

Solution 3:[3]

"nonlocal" means that a variable is "neither local or global", i.e, the variable is from an enclosing namespace (typically from an outer function of a nested function).

An important difference between nonlocal and global is that the a nonlocal variable must have been already bound in the enclosing namespace (otherwise an syntaxError will be raised) while a global declaration in a local scope does not require the variable is pre-bound (it will create a new binding in the global namespace if the variable is not pre-bound).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ManuelSchneid3r
Solution 2 blackgreen
Solution 3 Youjun Hu