0

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Ovi
  • 573
  • 2
  • 5
  • 16

5 Answers5

3

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()
ᔕᖺᘎᕊ
  • 2,971
  • 3
  • 23
  • 38
3

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)
Community
  • 1
  • 1
That1Guy
  • 7,075
  • 4
  • 47
  • 59
1

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.

Martin Lear
  • 262
  • 1
  • 7
0

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())
juanmajmjr
  • 1,055
  • 7
  • 11
0

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)
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24