+ 3
What is the real purpose of using return statement?
Please explain me with example
3 Answers
+ 7
If you make a function and use a local variable(variable that exists only inside the function) you need to use return to get the value out of the function.
def stuff():
a = 4
return a
If you donât return a you wonât be able to access it outside of the function.
+ 2
For example, imagine someone told you to make a function that sum to numbers. You may do it like this:
def sum(x, y):
print(x + y)
It works.
But imagine now that they tell you to take the result of the function and divide it by 2 to get the average.
What the person wants is a way to use the sum function like this:
result = sum (10, 16)
print(result / 2)
or
def average(x, y):
print(sum(x, y) / 2)
The only way is using a 'return' statement in the sum function.
Try it!
+ 1
Thkz alot guys, now i know how important is the return statement