Search code examples
pythonvariablesreturn-value

Returning Variables in Functions Python Not Working Right


I have been trying to return a variable in a function in a variable and use it outside of it:

test = 0

def testing():
    test = 1
    return test

testing()
print(test)

But when I run it, the result is 0. How could I fix this problem?


Solution

  • You are messing up a bit the scopes and/or assignment. Try this:

    def testing():
        test = 1
        return test
    
    test = testing()
    print(test)
    

    Explanation: The test inside testing is different to the test inside the module. You have to assign it on module-level to get the expected result.