the return statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

the return statement

I'm trying to understand the return statement and its role in a function definition. For example, I wrote this: def square(a): b=1 c=a*a+b print(a, "says hello to", c) return(c) square(5) The output was: 5 says hello to 26 So far so good. Then I noticed that I by mistake wrote return(b) instead of return(c) but that didn't change the output. So I wrote return(a) instead and it didn't change the output. Only when I put a letter that hasn't been defined did I change the output (to an error message). Finally I removed the return statement and only wrote following: def square(a): b=1 c=a*a+b print(a, "says hello to", c) square(5) Again the output was:5 says hello to 26 The output is the same regardless of the return statement being in the code or not. So I don't understand the purpose of writing the return statement. What does it contribute to the output?

30th Jan 2020, 8:42 PM
Goran
3 Answers
+ 1
It's because your printing inside the function, so for this to output the return statement not needed.
30th Jan 2020, 9:14 PM
rodwynnejones
rodwynnejones - avatar
+ 3
A function is a piece of code that only runs if you call it in your code, and after it's over, it will forget all its values and start over, when you call it again. If you want to use the result of what your function calculated, you have to return it from the function to the main code. The value will show up at exactly the spot where you called the function. def whatsthisabout(x, y): return 1/(x+y) result = whatsthisabout(3, 7) # result has become the return value print(result)
30th Jan 2020, 9:51 PM
HonFu
HonFu - avatar
+ 1
In short: return statement gives your function value so you can compare and do other things similar to variable. Example if you used return statement in your function: if (square(5)==5) print("true") It will print true. If you don't write return statement in your function it will throw exception.
30th Jan 2020, 8:54 PM
Amar
Amar - avatar