Search code examples
pythonglobal-variablesglobal

using an uninitialized global variable throws NameError


This code throws NameError: name 'x' is not defined":

def function():
    global x
    print(x)

function()
print(x)

However, this code works and prints "2" two times:

def function():
    global x
    x = 2
    print(x)

function()
print(x)

My question is, what actually happens at the moment x is declared as global?


Solution

  • You have not defined x, resulting in the errors. Try and make the function have a parameter of x.

    def function(x):
        print(x)
    

    Also, when you globalize a variable, its scope is not just within the function, but in every function/class.

    • Carden