Python functions
function
Mathematical definition
- y=f(x), y is a function of X and X is an independent variable. y=f(x0, x1, ..., xn)
Python functions
-
It is composed of statement block, function name and parameter list composed of several statements. It is the smallest unit of organizing code
-
Complete certain functions
Function function
-
Structured programming is the most basic encapsulation of code. Generally, a piece of code is organized according to function
-
The purpose of encapsulation is to reuse and reduce redundant code
-
The code is more concise, beautiful and readable
Classification of functions
-
Built in functions, such as max(), reversed(), etc
-
Library functions, such as math Ceil () et al
-
Custom function, defined with def keyword
Definition of function
def Function name(parameter list): Function body (code block) [return Return value]
-
The function name is the identifier, and the naming requirements are the same
-
The statement block must be indented with 4 spaces
-
Python functions that do not have a return statement implicitly return a value of None
-
The parameter list in the definition is called formal parameter, which is just a symbolic expression (identifier), abbreviated as formal parameter
function call
-
Function definition only declares a function, which cannot be executed and needs to be called for execution
-
The method of calling is to add parentheses after the function name, and fill in the parameters in parentheses if necessary
-
The parameters written during the call are actual parameters, which are actually passed in values, and are referred to as actual parameters for short
def add(x, y): # Function definition result = x + y # Function body return result # Return value out = add(4,5) # A function call may have a return value, and a variable is used to receive the return value print(out) # The print function with parentheses is also called
The above code explanation:
-
Define a function add, and the function name is add, which can accept 2 formal parameters
-
The result calculated by this function is returned by the return value. A return statement is required
-
When calling, add 2 actual parameters after the function name add, and the return value can be received using variables
-
The function name is also an identifier
-
The return value is also a value
-
The definition needs to be defined before the call, that is, during the call, otherwise the NameError exception will be thrown
-
Function is a callable object, and callable(add) returns True
See if this function is universal? Experience the benefits of Python functions
Function parameters
When defining a function, formal parameters should be defined, and sufficient actual parameters should be provided when calling. Generally speaking, the number of formal parameters and actual parameters should be consistent (except variable parameters).
Parameter transfer mode
1. Position transfer parameter
When defining def f(x, y, z), call f(1, 3, 5) and pass in arguments in the order of parameter definition
2. Keyword parameters
When defining def f(x, y, z), call f(x=1, y=3, z=5) and use the name of the formal parameter to pass in the argument. If the name of the formal parameter is used, the order of parameter passing can be different from that of definition
The location parameter must be passed in before the keyword parameter. The location parameter corresponds to the location
def add(x, y): print(x) print(y) print('-' * 30) add(4, 5) add(5, 4) # In order, the x and y values are different add(x=[4], y=(5,)) add(y=5.1, x=4.2) # Keyword parameters are transferred by name, regardless of order add(4, y=5) # correct add(y=5, 4) # Error transmission parameter
Remember: parameter passing refers to the actual parameters passed in during the call. There are two ways.
The following are all formal parameter definitions.
Default value of formal parameter
The default value is also called the default value. You can add a default value to the formal parameter during function definition. Its function:
-
The default value of a parameter can be assigned to a parameter that is not given a default value when not enough arguments are passed in
-
When there are many parameters, you don't need to input all the parameters every time to simplify the function call
def add(x=4, y=5): return x+y Test call add(),add(x=5),add(y=7),add(6, 10),add(6, y=7),add(x=5, y=6),add(y=5, x=6),add(x=5, 6),add(y=8, 4),add(11, x=20) Can we define it this way def add(x, y=5) or def add(x=4,y) ?
# Define a function login with parameter names of host, port, username and password def login(host='localhost', port=3306, username='root', password='root'): print('mysql://{2}:{3}@{0}:{1}/'.format(host, port, username, password)) login() login('127.0.0.1') login('127.0.0.1', 3361, 'wayne', 'wayne') login('127.0.0.1', username='wayne') login(username='wayne', password='wayne', host='www.baidu.com')
Variable parameters
Requirements: write a function that can accumulate and sum multiple numbers
def sum(iterable): s = 0 for x in iterable: s += x return s print(sum([1,3,5])) print(sum(range(4)))
In the above example, an iteratable object is passed in and each element is accumulated.
You can also use variable parameters to complete the above functions.
def sum(*nums): sum = 0 for x in nums: sum += x return sum print(sum(1, 3, 5)) print(sum(1, 2, 3))
1. Variable position parameter
-
Use * before the formal parameter to indicate that the formal parameter is a variable position parameter and can accept multiple arguments
-
It organizes the collected arguments into a tuple
2. Variable keyword parameter
-
Use * * before the formal parameter to indicate that the formal parameter is a variable keyword parameter and can accept multiple keyword parameters
-
It organizes the names and values of the collected arguments into a dict
def showconfig(**kwargs): for k,v in kwargs.items(): print('{}={}'.format(k,v), end=', ') showconfig(host='127.0.0.1', port=8080, username='wayne', password='baidu')
Mixed use
Can it be defined in the following ways? def showconfig(username, password, **kwargs) def showconfig(username, *args, **kwargs) def showconfig(username, password, **kwargs, *args) # ? no
Summary:
-
There are variable location parameters and variable keyword parameters
-
The variable position parameter uses an asterisk before the formal parameter*
-
Variable keyword parameters use two asterisks before the formal parameter**
-
Both variable location parameters and variable keyword parameters can collect several arguments. The variable location parameters are collected to form a tuple
-
Keyword parameters are collected to form a dict
-
When mixing parameters, ordinary parameters need to be placed in front of the parameter list, variable parameters need to be placed behind the parameter list, and variable position parameters need to be placed before variable keyword parameters
Use examples
def fn(x, y, *args, **kwargs): print(x, y, args, kwargs, sep='\n', end='\n\n') fn(3, 5, 7, 9, 10, a=1, b='abc') fn(3, 5) fn(3, 5, 7) fn(3, 5, a=1, b='abc') fn(x=1, y=2, z=3) fn(x=3, y=8, 7, 9, a=1, b='abc') # ? yes fn(7, 9, y=5, x=3, a=1, b='abc') # ? no
fn(x=3, y=8, 7, 9, a=1, b='abc '), the wrong position. The parameter must be passed before the keyword parameter
fn(7, 9, y=5, x=3, a=1, b='abc '), the error is that 7 and 9 have passed parameters according to the position, and x=3 and y=5 have repeated parameters
Keyword only parameter
Let's look at a piece of code first
def fn(*args, x, y, **kwargs): print(x, y, args, kwargs, sep='\n', end='\n\n') fn(3, 5) # no fn(3, 5, 7) # no fn(3, 5, a=1, b='abc') # no fn(3, 5, y=6, x=7, a=1, b='abc') #yes
After Python 3, the keyword only parameter is added.
Keyword only parameter: a common parameter that appears after a * asterisk or a variable position parameter when defining a formal parameter,
It is no longer an ordinary parameter. It is called keyword only parameter.
def fn(*args, x): print(x, args, sep='\n', end='\n\n') fn(3, 5) #no fn(3, 5, 7) #no fn(3, 5, x=7)
Keyword only parameter means that this parameter must be passed by keyword.
It can be considered that in the above example, the args variable location parameter has intercepted all location parameters, and the subsequent variable x cannot be passed in through the location parameter
Think: def fn(**kwargs, x) ok?
def fn(**kwargs, x): print(x, kwargs, sep='\n', end='\n\n')
Direct syntax error.
It can be considered that kwargs will intercept all keyword parameters. Even if x=5 is written, X has no chance to get this value, so this syntax does not exist.
Another form of keyword only parameter
*After the asterisk, all common parameters become keyword only parameters.
def fn(*, x, y): print(x, y) fn(x=6, y=7) fn(y=8, x=9)
Positional only parameter
Starting from Python 3.8, the definition of the last formal parameter type has been added: the positional only parameter. (released in October 2019, 3.8.0)
def fn(a, /): print(a, sep='\n') fn(3) fn(a=4) # Error, only positional parameters, can not use keywords to pass parameters
Mixed use of parameters
# Variable location parameter, keyword only parameter, default value def fn(*args, x=5): print(x) print(args) fn() # Equivalent to fn(x=5) fn(5) fn(x=6) fn(1,2,3,x=10)
# Common parameter, variable location parameter, keyword only parameter, default value def fn(y, *args, x=5): print('x={}, y={}'.format(x, y)) print(args) fn() # no fn(5) fn(5, 6) fn(x=6) #no fn(1, 2, 3, x=10) fn(y=17, 2, 3, x=10) # no fn(1, 2, y=3, x=10) # no fn(y=20, x=30)
# Common parameter, default value, variable keyword parameter def fn(x=5, **kwargs): print('x={}'.format(x)) print(kwargs) fn() fn(5) fn(x=6) fn(y=3, x=10) fn(3, y=10) fn(y=3, z=20)
Parameter rule
The general order of parameter list parameters is: positive only parameter, normal parameter, default parameter, variable location parameter, keyword only parameter (with default value) and variable keyword parameter.
be careful:
-
Code should be easy to read and understand, not to embarrass others
-
Please define function parameters according to writing habits
def fn(a, b, /, x, y, z=3, *args, m=4, n, **kwargs): print(a, b) print(x, y, z) print(m, n) print(args) print(kwargs) print('-' * 30) fn(1, b=2,y=3, x=10,n=5) #no fn(1, 2,y=3, x=10,n=5) # yes def connect(host='localhost', user='admin', password='admin', port='3306', **kwargs): print('mysql://{}:{}@{}:{}/{}'.format( user, password, host, port, kwargs.get('db', 'test') )) connect(db='cmdb') # The default values of parameters have written the most commonly used default values connect(host='192.168.1.123', db='cmdb') connect(host='192.168.1.123', db='cmdb', password='mysql')
-
The most commonly used parameters are defined as common parameters. Default values are not required and must be provided by the user. Note the order of these parameters. The most commonly used parameters are defined first
-
Define the parameters that can only be used with names as keyword only parameters. It is required to use keywords to pass parameters
-
If a function has many parameters and cannot be defined one by one, variable parameters can be used. If you need to know the meaning of these parameters, use variable keyword parameter collection
Parametric deconstruction
def add(x, y): print(x, y) return x + y add(4, 5) add((4, 5)) # OK? no t = 4, 5 add(t[0], t[1]) add(*t) add(*(4, 5)) add(*[4, 5]) add(*{4, 5}) # Pay attention to the order? add(*range(4, 6)) add(*{'a':10, 'b':11}) # OK? yes add(**{'a':10, 'b':11}) # OK? no add(**{'x':100, 'y':110}) # OK? yes
Parameter deconstruction:
-
When providing arguments to a function, you can use * or * * to deconstruct the structure before the iteratable object, and extract all the elements as the arguments of the function
-
Use * solution to form position transfer parameters
-
Use * * solution to form keyword parameters
-
The number of extracted elements should match the requirements of the parameters
def add(*nums): result = 0 for x in nums: result += x return result add(1, 2, 3) add(*[1, 3, 5]) add(*range(5))
# After 3.8, the following keywords can not be used to pass parameters after dictionary deconstruction def add(x, y, /): # Position parameters only print(x, y) return x + y add(**{'x':10, 'y':11})
Function return value
Let's start with a few examples
# Can I execute after the return statement? def showplus(x): print(x) return x + 1 print('~~end~~') # Will it be executed after return? no showplus(5) # Will multiple return statements be executed no def showplus(x): print(x) return x + 1 return x + 2 showplus(5) # Can multiple return s be executed in the following example? def guess(x): if x > 3: return "> 3" else: return "<= 3" print(guess(10)) # What is the result of the execution of the following functions def fn(x): for i in range(x): if i > 3: return i else: print("{} is not greater than 3".format(x)) print(fn(5)) # Print what? print(fn(3)) # Print what?
summary
-
Python functions use a return statement to return a return value
-
All functions have return values. If there is no return statement, return None is implicitly called
-
The return statement is not necessarily the last statement in the statement block of the function
-
A function can have multiple return statements, but only one can be executed. If no return statement is executed, return None is implicitly called
-
If necessary, you can display and call return None, which can be abbreviated as return
-
If the function executes a return statement, the function will return, and other statements after the currently executed return statement will not be executed
-
Function of return value: end function call and return "return value"
Can I return multiple values at once?
def showvalues(): return 1, 3, 5 showvalues() # Multiple values returned? no returns tuples
-
A function cannot return multiple values at the same time
-
Return 1, 3 and 5 seem to return multiple values, which are implicitly encapsulated into a tuple by python
-
x. Y, z = showlist() is more convenient to extract the return value using deconstruction