+ 1
What is the benifet of return in python?(with examples please) ما فائده الreturn ؟؟في بايثون
8 Respuestas
+ 3
Look, for example:
def func(x,y)
print(x+y)
func(7,4)
This is right. You have to leave at least one white space in the back of your print statement. Your code won't print desired value. (PRINT is NOT in def BLOCK.)
After that it'll print result, but if we print it, it's OVER and we can NOT use the result. To avoid this we'll change code:
def func(x,y)
return x+y # Function RETURNs a value.
print(x+y)
b = func(7,4) # We caught the result. The value that function RETURNs is 11.
b += 1 * 2 * 5 # We made some other processes on the result of func.
Now if you want you can print b. Output is 21.
As i said before if you didn't use return, your function wouldn't return the value.
In other word, without return:
def func(x,y)
print(x+y)
b = func(7,4) # We did NOT catch the value and missed it. b Value is NONE. We did NOT write RETURN in our function DEF.
b += 1 * 2 * 5 # b is NONE like a new variable, there is nothing in it. So we continue process with NONE variable.
Output is 10.
+ 3
For example, if you use Len() function, it'll return a value.
That value is the length of something like string.
Example:
a = Len("Hello")
print(a)
This code will print 5. The number of hello characters.
Now another use of RETURN can be when you want to define your own function.
Example:
def func(x,y)
return x+y
This code will return a value that you can catch it with this little code.
Example:
b = func(7,4) # We assigned returned value to a variable.
In fact If you didn't use return in your function, it wouldn't return anything and you couldn't catch the result.
In the code above we set x=7, y=4
Our function will return 11 and we'll catch it by assigning to b variable.
You can print(b) that equals to 11.
+ 3
Yes you can, but if you print it, you can NOT use it in another side of code.
If you want to make some change on the result of that function you need to assign it to a variable. Then you can use that value for other processes or calculations.
+ 3
Check out updated answer my friend.
+ 3
On my pleasure.
+ 1
but I can do this
def func(x,y)
print(x+y)
func(7,4)
and I will have the same output..!
+ 1
how
+ 1
thank u very much☺