python nested functions get variables from function scope

def a():
    val = True
    def b():
        nonlocal val
        val = False

Here is what the above code is Doing:
1. Defining a function a()
2. Defining a function b() inside a()
3. Declaring a nonlocal variable val inside b()
4. Assigning a value to val inside b()

Now, let’s see what happens when we call a():

>>> a()
>>> val
False

As you can see, the value of val is False.

This is because, when we call a(), the function b() is executed, which changes the value of val to False.

Now, let’s see what happens when we try to access val outside the function a():

>>> val
Traceback (most recent call last):
File ““, line 1, in
NameError: name ‘val’ is not defined

As you can see, we get an error because val is not defined outside the function a().

This is because, the variable val is declared as a nonlocal variable inside the function b().

This means that the variable val can only be accessed inside the function b().

Now, let’s see what happens when we try to access val inside the function a():

>>> a()
>>> val
False

As you can see, the value of val is False.

This is because, when we call a(), the function b() is executed, which changes the value of val to False.

Now, let’s see what happens when we try to access val outside the function a():

>>> val
Traceback (most recent call last):
File ““, line 1, in
NameError: name ‘val’ is not defined

As you can see, we get an error because val is not defined outside the function a().

This is because, the variable val is declared as a nonlocal variable inside the function b().

This means that the variable val can only be accessed inside the function b().