'python giving NameError with global variable
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)
Solution 1:[1]
cnt is just in my_func() and add_one() can't find it. You should global it in My_func() and then add_one() can access it
def my_func():
cnt = 0
global cnt
def add_one():
cnt = cnt + 1
print(cnt)
add_one()
print(cnt)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Player01 |
