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)
CodePudding user response:
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)
CodePudding user response:
In python, the variable has three scopes: local, nonlocal and global.
- A variable in a function, the variable's scope is local.
- A variable outside of a function, the variable's scope is global.
- For nested functions, if a variable is in the outer function, its scope is nonlocal for the inner function. If the inner function wants to access the variable in the outer function, need to use
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