Python basic syntax _ function _ return value and python basic syntax
Python basic syntax
Summary:
The return value of a function is an important part of a function. The root of a function is to implement some functions of the program. Therefore, we often need to return the result after the function is executed to the program for further operations. It can be said that the return value of a function makes the function more closely linked with the main program.
Function return value
Each function in Python has a return value. The default value is None. You can also use the return value statement to define one and only one return value that can be of any type. However, we can return an object of the sequence type to return multiple values.
Example:
Returns a List
In [11]: %pycat reTest.py#!/usr/bin/env pythondef testReturn(input1,input2): sum = input1 + input2 return [sum,input1,input2]calculation = testReturn(1,2)x,y,z = testReturn(1,2)print calculationprint xprint yprint zIn [12]: run reTest.py[3, 1, 2]312
Differences between Return and Print in Functions
Many beginners will confuse the differences between the two. In general, return returns and ends the function, while print only prints the output. The following is an example:
In [25]: %pycat reTest.py#!/usr/bin/env pythondef testReturn(input1): for i in range(input1): return idef testPrint(input1): for i in range(input1): print in = 3value1 = testReturn(n)print 'testReturn return value = %s' % value1 print '*'*15value2 = testPrint(n)print 'testPrint return value = %s' % value2In [26]: run reTest.pytestReturn return value = 0***************012testPrint return value = None
The above example shows the difference between the two.
Return:After the function is called, return returns 0 and assigns it to value1, and ends the function. Therefore, only 0 is returned.
Print:The loop prints all values 0 1 2, but because the function does not have the return value defined by the return Statement, the default value of None is returned and assigned to value2.
Function documentation
By the way, this Document introduces the function. The Python function documentation defines the function using "Document" In the next line of the Function Definition Statement and uses functionName. _ doc _ to print the document information of the function.
Example:
View the document of a built-in Function
In [12]: number = 123In [13]: number.__add__.__doc__Out[13]: 'x.__add__(y) <==> x+y'
You can see that the function documentation is very useful. A clear and concise document can help you quickly master the usage of a function.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!