0

Why is it that a variable declared inside the main block is not visible to a function declared inside that same main block?

And what should I do to make code that is structured like this work as intended?

if __name__ == "__main__":
    foo = 0
    def bar():
        foo +=1
    bar()




Traceback (most recent call last):
  File "C:\Users\Mark\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-fa3c4c1d4159>", line 5, in <module>
    bar()
  File "<ipython-input-3-fa3c4c1d4159>", line 4, in bar
    foo +=1
UnboundLocalError: local variable 'foo' referenced before assignment
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 1
    `foo` is not declared in the `bar` function and you're trying to access it before declaration. If you want to use `foo` from the outer scope, you'll have to declare `global foo` explicitly before attempting `foo += 1`. – zwer Apr 14 '18 at 00:05
  • 1
    Note, Python *does not have variable declarations*, nor does it have block scope. The `foo` in the `if` block is global. Because you assign to `foo` inside `bar`, the compiler automatically makes `foo` local unless you use a `global foo` statement inside `bar` – juanpa.arrivillaga Apr 14 '18 at 00:18

0 Answers0