-1

I use the following code to experiment with nonlocal

def a():
    b = 5
    print(f"b (1) = {b}")
    def c():
        #nonlocal b
        print(f"b (2) = {b}")
        b = 3
    c()

a()

When I comment out nonlocal I get the following error:

Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "<string>", line 8, in a
  File "<string>", line 6, in c
UnboundLocalError: cannot access local variable 'b' where it is not associated with a value

I expected the value of variable b from function a to be printed out on the console and then a locale variable of the same name would be created. But obviously when the function is parsed, it is noted that there is a local variable called b in the function c, but it is not yet assigned a value, as this is done at runtime. Are my thoughts correct and are there sources where I can read more about this?

1 Answers1

1

yup , you're correct When you comment out the nonlocal statement, Python treats b as a local variable inside function c(). Therefore, trying to access it before assigning a value results in an UnboundLocalError. If you want to modify the variable b defined in the outer scope within the inner function c(), you need to use the nonlocal keyword.

but you can also achieve your desired output without nonlocal, just by passing the variable b as an argument to the inner function c().his way, you're providing the value of b to the inner function and avoiding the scope-related issues.

def a():
    b = 5
    print(f"b (1) = {b}")
    
    def c(b):  
        print(f"b (2) = {b}")
        b = 3
    
    c(b)  

a()
vegan_meat
  • 878
  • 4
  • 10