0

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()

1 Answers1

0

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

Meny Issakov
  • 1,400
  • 1
  • 14
  • 30