Python variable scopes explained

In Python, understanding variable scope is crucial for writing clean and effective code. The scope of a variable determines where it can be accessed and modified within your program. Python uses a hierarchical rule known as LEGB, which stands for Local, Enclosing, Global, and Built-in scopes. Each of these levels has its own significance, dictating how Python resolves variable names. Check out the code below. Do you know what will be printed out? If you are unsure see the explanation below.

    x = 100
    def layer1_function():
        x = 1
    
        def layer2_function():
            nonlocal x
            x = 2
    
            def layer3_function():
                x = 3
    
                def layer4_function():
                    nonlocal x
                    x = 4
                    print("Layer 4 x:", x)
    
                layer4_function()
                print("Layer 3 x:", x)
    
            layer3_function()
            print("Layer 2 x: ", x)
    
        layer2_function()
        print("Layer 1 x:", x)

    layer1_function()
    print("Global x: ", x)

And the output of the code is the following.

Layer 4 x: 4
Layer 3 x: 4
Layer 2 x:  2
Layer 1 x: 2
Global x:  100