Home > Backend Development > Python Tutorial > python study notes-defining functions

python study notes-defining functions

高洛峰
Release: 2016-11-15 14:55:48
Original
1601 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login

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
Copy after login

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()
Copy after login

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().

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template