function return value
Through the above learning, you can know that the return [expression] statement is used to exit the function and selectively return an expression to the caller. A return statement without a parameter value returns None.
Specific example:
# -*- coding: UTF-8 -*- 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:
3
This example also performs data type checking through the built-in function isinstance() to check whether the parameters when calling the function are integer and Floating point type. If the parameter type is incorrect, an error will be reported, indicating that the parameter type is wrong, as shown in the figure:
Of course, the function can also return multiple values. The specific example is as follows:
# -*- coding: UTF-8 -*- 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:
2.0 1 (2.0, 1)
If you observe carefully, you can find that although multiple values are returned from the first output value, a tuple is actually created first and then returned. Recall that tuples can be created directly using commas. Looking at ruturn in the example, you can see that we actually use commas to generate a tuple.