Search code examples
pythonvariablesnameerror

python cant call a global variable


Edit: problem solved why are you still giving negative points

i created a function like this:

def testFunc():
    global testVar

    if True:
        testVar = input("input something: ")

def anotherFunc():
    if testVar == "test":
        print("okay")

anotherFunc() #calling function

but im getting an error:

File "C:/Users/jeffpc/Desktop/Files/wqw.py", line 8, in anotherFunc
if testVar == "test":
NameError: name 'testVar' is not defined

what is the problem here?


Solution

  • The statement global testVar is not at all executed as per your code snippet. You need to either declare the global variable outside testFunc() or call it before calling anotherFunc()

    In case of your code, below is the right solution as testVar is not just initialized but also assigned value inside testFunc()

    def testFunc():
        global testVar
    
        if True:
            testVar = input("input something: ")
    
    def anotherFunc():
        if testVar == "test":
            print("okay")
    
    testFunc()
    anotherFunc()