In python, the key word for defining a function is def. for example, we can define a function called my_function. the x and y in parentheses are input parameters. In python, the key word for defining a function is def. for example, we can define a function called my_function. the x and y in parentheses are input parameters.
def my_function(): # function body
Return value
The function can return data with the keyword return. When the function is executed to return, the function is no longer executed. No function used to write the return statement. by default, None is returned.
Return None can be abbreviated as return.
Empty function
If you want to define a function that does nothing, you can use the pass statement.
For example
def do_nothing() pass
Pass serves as a placeholder. If the specific content of this function does not need to be defined, you can use pass.
Parameter check
The previous article introduced that built-in functions will check the number and data type of input parameters. So how does python handle user-defined functions?
We define a function.
def my_function(x,y): return x*y
Call: my_function (1, 2, 3)
Error:
Traceback (most recent call last): File "/Users/W/Code/Python/LearnPython/DataType.py", line 4, in
my_function(1,2,3)TypeError: my_function() takes exactly 2 arguments (3 given)
Call: my_function (1, "abc ")
Error: no error message is returned. In fact, we hope that the two parameters passed in by my_function should be integers that are only applicable to floating point numbers.
Add parameter checks for functions
Let's rewrite my_function.
def my_function(x, y): if not (isinstance((x,y),(int,float)) and isinstance(y,(int,float))): raise TypeError('Bad operand type') return x*y
When the my_function function is called, if an incorrect parameter is input, a TypeError is thrown.
The function returns multiple values.
Python supports returning multiple values. Python is actually implemented by returning a tuple. We can verify it through a simple demo:
def func(): return 2, 3print func()
The output is a tuple (2, 3.
In syntax, a tuple can be returned without parentheses, that is, multiple variables can receive a tuple at the same time and assign the corresponding value by position. For example
X, y = func ().