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?
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.
Because you declare test
in the function, it is not a global variable, thus, you can not access the variable test
you created in the function outside of it as they are different scopes
If you want to return test
to a variable, you have to do
result = testing()
print(result)
Or, you can also add a global
statement:
test = 0
def testing():
global test
test = 1
return test
testing()
print(test)
By the way, when doing a conditional statement, you don't need the brackets around the 1==1
:).
Inside the function testing()
, you're creating a new variable test
, not referring to the one that already exists. If you want to do that, you should use a global
statement in the top, as in:
def testing():
global test
...etc...
Your test
variable inside the function does not have a global scope. So, if you want to store the return value in a variable and output it after that, you can do something like this:
result = testing()
print(result)