-4

I am creating a program, and I have shortened the code to this to try and work out why the return statement is not working and printing the new value of 'answer' after I have run it through my function. It is saying that the answer variable is not defined. But I have tried to set the answer to zero at the start of the program to see if this will solve the issue, but this just prints 0.

Here is my code:

def addition():
    answer = 1+2
    return answer
addition()
print(answer)

I hope you can help :) Thank you

coder1234
  • 51
  • 1
  • 1
  • 10
  • 2
    `print(addition())` or `answer = addition() `then `print answer` – Ehsan May 14 '20 at 07:41
  • 3
    Use a variable to get the returned value.Like `result = addition()` then `print(result)`. – jizhihaoSAMA May 14 '20 at 07:41
  • 1
    `return foo` doesn't mean the caller has a `foo` variable now. `return` doesn't pass variables around. Nothing in Python does that. – user2357112 May 14 '20 at 07:45
  • 2
    Does this answer your question? [Returning Variables in Functions Python Not Working Right](https://stackoverflow.com/questions/18039530/returning-variables-in-functions-python-not-working-right) – Kevin Mayo May 14 '20 at 08:12

3 Answers3

2

answer is a variable that is local to the addition function. You would have to assign the result of the function call to a variable in the current namespace:

def addition():
    answer = 1+2
    return answer

x = addition()
print(x)
# or simply
print(addition())
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

try

print(addition())

you are calling the function but saving the return value in a variable

or you can use save the return value in a variable and print that

ans = addition()
print('Ans = '+ans)
Ragul M B
  • 204
  • 3
  • 9
1
def addition():
    answer = 1+2
    return answer

print(addition())

And if you like to do one more step:

def addition(a ,b):
    answer = a+b
    return answer

print(addition(1,2))
Marco
  • 1,952
  • 1
  • 17
  • 23