Home  >  Article  >  Backend Development  >  python study notes-defining functions

python study notes-defining functions

高洛峰
高洛峰Original
2016-11-15 14:55:481580browse

The keyword for defining functions in Python is def. For example, to define a function called my_function, we can define it like this, where x and y in parentheses are the parameters passed in.

def my_function():
    # function body

Return value

The function can return data using the keyword return. When the function is executed until return, it returns and no longer executes the function. Functions without return statements return None by default.
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 acts 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 the built-in function will check the number and data type of the parameters passed in. So how does Python handle custom 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 <module>
    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 and floating point numbers.

Add parameter checking to the function

We make some changes to my_function.

def my_function(x, y):
    if not (isinstance((x,y),(int,float)) and isinstance(y,(int,float))):
        raise TypeError(&#39;Bad operand type&#39;)
    return x*y

At this time, when calling the my_function function and passing in wrong parameters, a TypeError will be thrown.

Function returns multiple values

Python supports returning multiple values. Python actually implements this by returning a tuple. We can verify it through a simple demo:

def func():
    return 2, 3
print func()

will output a tuple like (2,3).
In terms of syntax, parentheses can be omitted when returning a tuple, that is, multiple variables can receive a tuple at the same time and assign the corresponding value according to position. For example
x,y = func().

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn