Home > other >  Traceback (most recent call last): UnboundLocalError: local variable referenced before assignment
Traceback (most recent call last): UnboundLocalError: local variable referenced before assignment

Time:12-12

why am I getting mentioned error? Is there any better way to do this?

def a():
  t = 0
  def b():
    t =1
    return  
  b()
  print(t)
a()

CodePudding user response:

You can use the nonlocal statement which will bind access to the t variable from a function. Though, I wouldn't use that approach unless required.

def a(): t = 0
def b(): nonlocal t t = 1 return
b() print(t) a()

More information can be found here: Python nested functions variable scoping

  • Related