Can someone please help me understand why this is throwing a NameError? I'm defining and initializing 'cnt', then declaring it as a global, but I'm getting a NameError that 'cnt' is not defined.
def my_func():
cnt = 0
def add_one():
global cnt
cnt = cnt + 1
print(cnt)
add_one()
print(cnt)
In python, the variable has three scopes: local, nonlocal and global.
nonlocal
keyword.So, change global cnt
to nonlocal cnt
, the code will be work.
This document may help you understand variable scopes in python:
Python Scope of Variables