
2. Function return value
Through the above study, you can know that the return [expression] statement is used to exit the function, selectively returning an expression to the caller.
A return statement with no parameter value returns None.
Concrete example:
def sum(num1,num2):
if not (isinstance (num1,(int ,float)) and isinstance (num2,(int ,float))):
raise TypeError('参数类型错误')
return num1+num2
print(sum(1,2))
Return result:
This example also isinstance()
performs data type checking with built-in functions to check if the arguments are integers and floats when the function is called. If the parameter type is incorrect, an error will be reported, as shown in the 参数类型错误
,
figure :

Of course, the function can also return multiple values, the specific examples are as follows:
def division ( num1, num2 ):
a = num1 % num2
b = (num1-a) / num2
return b , a
num1 , num2 = division(9,4)
tuple1 = division(9,4)
print (num1,num2)
print (tuple1)
Output value:
If you look closely, you can see that although multiple values are returned from the first output value, a tuple is actually created and then returned.
Recall that tuples can be created directly with commas. Observe return in the example, and you can see that we are actually using commas to generate a tuple.
The function return value in the Python language can be multiple, but other languages cannot. This is the simplicity and flexibility of Python compared to other languages.
The data type that Python accepts multiple return values at once is a tuple.
I don’t know if you still remember the relevant knowledge of tuples at this moment. If you don’t remember, it is recommended to write a few examples to recall immediately, such as how to get the first element of the tuple.
Featured Article Recommendations
Follow me and catch the latest and most trendy black technology together
Zongshi Technology
Catch the latest and most trendy black technology~
12 original content
the public