- 1
Return statement
at the moment, i still did not know why did i need to use return... i hope someone can explain to me by using example.
4 Answers
+ 3
@alif OK, maybe print() was not a good example...
If the above functions were defined in order to assign their values to variables, like:
f1 = fun1(10)
f2 = fun2(10)
Each of the f variables would be equal to what a particular function returns. In that case, f1 would be equal to None, as the fun1 function does not return anything. f2, on the other hand, would equal 13.
+ 2
You use return in the function for it to pass on a value to the rest of the code. Take a look:
def fun1(x):
x += 2
def fun2(x):
x += 3
return x
Now:
print(fun1(10)) - will print out "None" as the function did the addition but did not pass this value outside. x was only incremented inside the function.
print(fun2(10)) on the other hand - will do the addition and return the new value of x outside the function - it will print out 13.
+ 1
You use return when you want a function to return a value. So, if your function calculates say x + y = z, then you would return z. Hope that makes sense.
0
yeah, but why we have to use return instead of print(x)?