Usage of return in python
1、 The return statement is to return the execution result to the calling place and return the control of the program together
The program will return after the first return encountered (exit the def block), and will not run the second return.
E.g:
defhaha(x,y):
ifx==y:
returnx,y
print(haha(1,1))
Result: This kind of return will return tuples(1,2)
2、 But it does not mean that there can only be one return statement in a function body, for example:
deftest_return(x):
ifx 0:
returnx
else:
return0
print(test_return(2))
3、 The function does not return, and returns a None object by default.
There is no return in the recursive function:
defrecurve(a,b):
ifa%b==0:
returnb
else:gcd(b,a%b)
Analysis: There is no exit if there is no return in the else, this program is running internally, and the program has no return value.
4、 In interactive mode, the result of return will be automatically printed out, but when running as a script alone, the print function is required to display it.
What is the interactive mode in python: there are 3 symbols () at the end. It is called the Python command prompt (prompt).
Enter a line of python code to execute the code, this mode is called Python interactive mode (interactive mode).
Knowledge point expansion:
Python implements return to return multiple values
The return statement of a function can only return one value, which can be of any type.
Therefore, we can "return a tuple type to indirectly return multiple values".
def F1( x, y ):
a = x % y
b =(x-a)/ y
return( a,b ) #Can also be written as return a,b(c, d )=F1(9,4) #Can also be written as c, d =F1(9,4)
print c ,d
The results show: 1, 2
So far, this article on how to write return in python is introduced. For more information about how to write return in python, please search for ZaLou.Cn's previous articles or continue to browse related articles below. I hope you will support ZaLou more in the future. Cn!
Recommended Posts