I tried the following and got an error message that "x is not defined".
def test():
x = 2
y = 3
return x
def main():
test()
print(2 + x)
main()
Why isn't it working?
I tried the following and got an error message that "x is not defined".
def test():
x = 2
y = 3
return x
def main():
test()
print(2 + x)
main()
Why isn't it working?
You need to assign x
again, and the way to do that is say x = test()
. The x
from test
only exists in x
, which is why you need to reassign it.
It doesn't even have to be x, it could be y
, or z
: x
is simply the name you return, the value you use in main()
can be called anything!
Or, you can just call the function directly in main()
, in which case you won't even need the first line in the main function:
def test():
x = 2
y = 3
return x
def main():
x = test()
print(2 + x) #or just `print(2 + test())`
main()
x
is defined in test
, but not in main
This means that x
is not defined in main
's scope
Take a look at this question for more details regarding scope. Specifically this answer.
If you want to use the value assigned to x
in test
, you need to assign the return value of test to a name:
def main():
value_of_x_from_test = test() # This is the same as `x = 2` in `test`.
print(2 + value_of_x_from_test)
It's not working because of scope. X is defined in test, but not in main(). Try setting x = test() in main, and everything should work for you.
Because of x is defined locally in test(), it cannot be used by main. Instead you can use directly the output of test as it is shown in the following code:
def main():
print(2 + test())
In order to get the value of x
in main()
, you have to assign it to something:
def main():
value = test() # The variable can be 'value' or any other valid name, including 'x'
print(2 + value)