-1

I've recently learned how to use "def" in Python and was messing about with it but then encountered an issue:

after assigning values to a variable within a function I'm defining, when trying to do something with that variable outside of the function, it seems like nothing was ever assigned to that variable? I'm not really sure.

def sum(x, y):
    test = x + y
sum(1, 2)
print(test)

When running this code, I expect the output to be 3 but it tells me that "test" is not defined.However I get my desired output when it's formatted this way:

def sum(x, y):
    res = x + y
    print(res)
sum(1, 2)
  • You need to read about variable scope and `return`. Have your function `return x + y` (rather than assign x+y to a local variable) and then use `print(sum(1,2))`. – John Coleman Dec 30 '22 at 13:40

2 Answers2

0

Your test exists only in the scope of the function.

When you exit the def block it doesn’t exist anymore.

That’s why your second example works as print(res) is also in the function scope.

ljmc
  • 4,830
  • 2
  • 7
  • 26
0

The variable test you have, is inside of the scope of the sum function. Thats also the reason why you can't access it outside of the function and the error says that "test is Undefined". You can fix this in a lot of ways than one: