-1

I know that this code can work.

def mom_func():
    temp = 0

    def son_func() :
        a = temp

and then why this code cannot work ?

def mom_func():
    temp = 0

    def son_func() :
        a = temp
        temp = 1

error message is Unresolved reference 'temp'

def mom_func():
    temp = 0

    def son_func() :
        a = temp
        print(a)

    son_func()

this code can work print '0' and when i have set temp to '7', then code printed '7' !

David Makogon
  • 69,407
  • 21
  • 141
  • 189
JaeEun Lee
  • 13
  • 4
  • 1
    In Python, when you assign a value to a variable inside a function, Python assumes that variable is local to the function, even if it has the same name as a variable in the outer scope. – Ake Apr 06 '23 at 04:22
  • When you modify a variable within a function, it makes that variable local to that function. To modify a variable in a containing function, you need to declare it `nonlocal`. To modify a global variable within a function, you need to declare it `global`. – Tom Karzes Apr 06 '23 at 04:23
  • thank you all ! 'nonlocal' is what i look for ! – JaeEun Lee Apr 06 '23 at 05:50

1 Answers1

0
def mom_func():
    temp = 0

    def son_func() :
        a = temp
        temp = 0
        print(a)

    son_func()

Here python assumes that temp is a local variable inside 'son' function, since it is assigned a new value (temp = 0) inside this function. So when you try to access its value before you assign it to 0 (temp = 0) inside the 'son' function you are getting an 'UnboundLocalError' as it remains unassigned before you write temp = 0 in the next line and raises an error.

To remove this error and access the temp variable from the 'mom' fucntion you have to assign the temp variable as nonlocal inside the 'son' function so that python won't assume it as local variable after we assign its value to 0 inside the 'son' function

def mom_func():
    temp = 0

    def son_func() :
        nonlocal temp
        a = temp
        temp = 0
        print(a)

    son_func()

I hope this would answer your question. Please reply back if you have any more doubt.

  • This is a duplicate question, and was marked as such (but not yet closed) long before you posted this answer. – Tom Karzes Apr 06 '23 at 05:12