为什么在主块内声明的变量对于在同一主块内声明的函数是不可见的?
我该怎么做才能使代码按照预期的方式构建?
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