0
foo = 1
def bar():
    print(foo)
    foo = 5

This function throws UnboundLocalError: local variable 'foo' referenced before assignment.

My question is, how does the interpreter know that foo is a local variable in this function, what does the interpreter do before it excutes a function?

Mumon
  • 1
  • 1
  • 1
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read [ask]. In the future, you need to try your own research, like Googling the error message. I found that question and a bunch more by searching `"UnboundLocalError: local variable referenced before assignment"`. That said, kudos for writing a super clear and concise question! – wjandrea Oct 12 '21 at 01:37
  • Yet another reason to avoid global vars at all costs :) Check out this video, you might find it interesting - https://www.youtube.com/watch?v=9v8eu4MOet8 – Fraser Langton Oct 12 '21 at 01:49

0 Answers0