Python basic syntax _ function _ return value

  • 2020-05-24 05:44:54
  • OfStack

Python explains the basic syntax

Summary:

The return value of a function is an important part of the function. The basic function is to realize part of the function of the program, so a lot of times we need to return the result of the function execution to the program and then the program to make a step forward. You could say that the return value of a function makes the functions more closely related to each other, to the main program.

The return value of the function

Each of Python's functions has a return value, which defaults to None. You can also use the return value statement to define one and only one return value of any type. However, we can return an object of sequence type to achieve the effect of returning multiple values.

Example:

Return 1 List


In [11]: %pycat reTest.py
#!/usr/bin/env python
def testReturn(input1,input2):
  sum = input1 + input2
  return [sum,input1,input2]

calculation = testReturn(1,2)
x,y,z = testReturn(1,2)
print calculation
print x
print y
print z

In [12]: run reTest.py
[3, 1, 2]
3
1
2


The difference between Return and Print in a function

Many beginners confuse the difference between the two, but the bottom line is that return returns the value and ends the function, while print is just a printout. Here is an example:


In [25]: %pycat reTest.py
#!/usr/bin/env python
def testReturn(input1):
  for i in range(input1):
    return i

def testPrint(input1):
  for i in range(input1):
    print i

n = 3
value1 = testReturn(n)
print 'testReturn return value = %s' % value1 

print '*'*15

value2 = testPrint(n)
print 'testPrint return value = %s' % value2

In [26]: run reTest.py
testReturn return value = 0
***************
0
1
2
testPrint return value = None

The above example clearly shows the difference between the two.

return: after calling the function, return returns 0 and assigns it to value1, ending the function at the same time. So you can only return 0.

print: the loop prints out all 0, 1, and 2, but since the function does not have a return value defined by the return statement, it returns the default None and assigns value2.

Document in a function

By the way, the document of function 1, Python function, is defined by using ""Document"" in the next line of the function definition statement, and USES functionName.s 54en__ to print the document information of the function.

Example:

View the documentation for one of the built-in functions


In [12]: number = 123

In [13]: number.__add__.__doc__
Out[13]: 'x.__add__(y) <==> x+y'

You can see the function documentation is a very useful thing, clear and concise documentation can make people quickly grasp the use of a function.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: