Search code examples
pythonnameerror

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

  • 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