function function:
What is a function: Afunction is a block of statements that can be executed repeatedly and can be called repeatedly
. Functions :
1. It is used to encapsulate repeatable statements and improve the reusability of statements.
2. Define user-level functions
The syntax of the function definition statement def statement:
def function name (parameter list):
Statement block (block of code)Syntax description of the function:
1. The name of the function is the name of the statement block2. The naming rule of the function name is the same as the naming rule of the variable name (it must be an identifier)
3. The function name is a variable (do not assign it lightly)
4. The name of the function itself Space, external variables can be accessed inside the function, but external statements cannot access variables inside the
function 5. If the function does not need to pass in parameters, the parameter list can be empty
. 6. The statement part cannot be empty. pass statement
Example 1:
def say_hello(): print('hello world') print ('hello tarena') print('hello everyone')
function call:
Function name (parameters passed by the actual call)Note:
The parameters passed by the actual call are referred to as 'actual parameters'
Calling instructions:
1. The function call is an expression2. If there is no return statement, the function returns None after the function is executed.
3. If the function needs to return other objects, you need to use the return statement
Example 2:
# Definition of a function with parameters # ! /usr/bin/python3 # This example schematically defines a function with parameters def mymax(a, b): if a > b: print('The maximum number is:', a) else: print('The maximum number is:', b) # Call a function with parameters, the first actual parameter 100 is given to the formal parameter a, the second... mymax(100, 200) mymax(10000, 5000)
The function definition format is as follows:
def print_even(n):pass
There is an independent running space inside the function, and the variables inside the function cannot be accessed outside the function
Example:# ! /usr/bin/python3 def test(): x = 100 # This variable is a local variable and can only be used inside a function print(y) # this is legal this function can access global variables outside the function y = 200 test() # call test # print(x) # There is no variable x at this time
return statement:
Syntax:return[expression]
Note: [] means that the content can be omitted
. Function:
used in a function to end the execution of the current function, return to the place where the function was called, and return an object's reference relationship
Description:
1. return statement The following expression can be omitted, which is equivalent to return None
2. If there is no return statement in the function, the function returns None after executing
the last statement (equivalent to adding a return None statement at the end)
3. Function call An example of a reference that can return an object
:
# ! /usr/bin/python3 # This example shows the usage of the return statement def hello(): print('hello world') print ('hello tarena') return # is used to return to where it was called print('hello everyone') v = hello () print(v)practise:
''' 1. Write a function mymax that returns the maximum value of two numbers: ''' def mymax(x, y): if x >= y: return x return y print(mymax(100, 200)) print(mymax(200, 100)) print(mymax('acd', 'abcd')) ''' 2. Write a function input_number() This function is used to read multiple integers entered by the user (end input when the user enters a negative number) Return the number entered by the user as a list to the caller ''' # method one # ! /usr/bin/python3 def input_number(): number = [] while True: n = int(input('Please enter a positive integer: ')) if n < 0: break number.append(n) return number if __name__ == '__main__': n = input_number() print(n) print('The maximum number you entered is', max(n)) print('The sum of the numbers you entered is', sum(n)) # Method Two # ! /usr/bin/python3 def input_number2(): number = [] while True: n = int(input('Please enter a positive integer: ')) if n < 0: return number number.append(n) if __name__ == '__main__': n = input_number2() print(n) print('The maximum number you entered is', max(n)) print('The sum of the numbers you entered is', sum(n))
Argument passing for python functions
Delivery method:
Position parametersequence parameter parameter
keyword parameter
dictionary keyword parameter parameter
Location parameter:
The correspondence between the actual call parameters (actual parameters) and the formal parameters (formal parameters) is an indication of one correspondence by position :
def fx(a, b, c):
pass
# ^ ^ ^
fx(1, 2, 3)
Sequence parameter transfer:
Sequence parameter transfer is a parameter method that disassembles the sequence with * and passes it by position in the process of calling the function. The
actual and formal parameters are passed and matched through the sequence
Example:
def fx(a, b, c):
pass
s1 = [11, 22, 33]
#List fx(*s1)# After disassembling the s1 sequence, pass it into fx by position
# ! /usr/bin/python3 # This example shows sequence parameter passing def fx(a, b, c): print('a=', a) print('b=', b) print('c=', c) s1 = [11, 22, 33] # index pass # fx (s1 [0], s1 [1], s1 [2]) # sequence parameter fx(*s1) # * means to talk about the dismantling of s1 and then pass it in in turn fx(*'ABC') fx(*(101, 202, 303)) # fx(*'ABCD') # wrong, there are four parameters in the sequence, but the formal parameters are three print(*'abc') # same as print('a','b','c')
Keyword parameters:
Refers to when passing parameters, assign values to the formal parameters according to the namesof the formal parameters and pip the formal parameters by name
Example:
def fx(a, b, c):
pass
fx(b=22, c=33, a= 11) # 11-->a, 22-->b, 33-->c
Note:
The actual parameter and the formal parameter are matched according to the formal parameter name, and can not be matched according to the position
#! /usr/bin/python3 def fx(a, b, c): print('a=', a) print('b=', b) print('c=', c) fx(b=22, c=33, a=11) # fx(b=22, c=33, b=55) # wrong
dictionary keyword argument
The actual parameter is a dictionary. After disassembling the dictionary with **, the keyword parameter is passed.Example:
def fx(a, b, c):
pass
d = {'c':33, 'b':22, 'a': 11}
fx(**d) # Disassemble the dictionary and pass the parameters by keyword in turn
. Instructions:
The key name of the dictionary and the formal parameter name must be consistent
. The key name of the dictionary must be a string
. The meeting of the dictionary must exist in the formal parameter
#! /usr/bin/python3 def fx(a, b, c): print('a=', a) print('b=', b) print('c=', c) d = {'c': 33, 'b': 22, 'a': 11} fx(**d) # Disassemble the dictionary and pass parameters by keyword in turn # fxc=33, b=22, a=11)
Comprehensive reference:
The parameter passing method of the function can be combined arbitrarily if it can be determined that the formal parameters can uniquely match the actual parameters of XingningNote:
Usually, the positional parameter passing and sequence passing are passed first, followed by keyword parameter passing and dictionary keyword parameter passing
Examples:
def fx(a, b, c, d, e, f):
pass
fx(10, *[20, 30], e=50, **{'d': 40, 'f': 60})
# The following is Bad practice
fx(e=50, **{'d': 40, 'f': 60}, 10, *[20, 30])
**************** ********The following will be the formal parameters of the function ************************
Default parameters for the function:
Syntax:def function name (parameter name 1=default parameter, parameter name 2=default parameter 2,...):
Statement
example:
#! /usr/bin/python3 def info(name, age=1, address='不详'): print('My name is', name, 'My year:', age, 'year old, home address:', address) info('Zhang Fei', 30, 'Central Plain') info ('Tarena', 10) info('Zhao Yun') # operation result My name is Zhang Fei My year: 30 Aged, Home Address: Central Plains My name is Tarena My year: 10 Age, Home Address: Unknown My name is Zhao Yun My year: 1 Age, Home Address: UnknownNote:
The default parameters must exist in order from right to left. There
can be zero, one or more, or even all
of the binding objects with default parameters and default parameters exist in the function, which is consistent with the life cycle of the function.
Important** Example:
def fn(a, lst=[]): # ***IMPORTANT**** ^ | # will not delete, no new list will be defined lst.append(a) print(lst) L = [1, 2, 3, 4] fn (5, L) # [1, 2, 3, 4, 5] fn (6, L) # [1, 2, 3, 4, 5, 6] fn(1.1) # [1.1] fn(2.2) # [1.1, 2.2]
How the formal parameters of the function are defined:
1. Positional parameter2. Asterisk tuple parameter
3. Named keyword parameter
4. Double asterisk dictionary parameter
Positional parameters:
def function name (parameter name 1, parameter name 2, ...):statement block
Asterisk tuple parameters:
Syntax:def function name (*tuple parameter name):
statement block
Action:
collect redundant positional parameters
Example:
#! /usr/bin/python3
# This example shows an asterisk tuple parameter def func(*args): print('The number of actual parameters is:', len(args)) print('The value of args is: ', args) func(1, 2, 3) func('ABCD', 3.14, 100, True, None)
Named keyword parameters:
Syntax:def function_name(*, named keyword parameters):
statement block
or
def function_name(*args, named keyword parameters):
statement block
Effect:
all named keyword parameters force the caller to use the keyword
Example of passing parameters or dictionary keyword parameters :
#! /usr/bin/python3 def myfun(a, *, k): print('a=', a) print ('k =', k) # myfun(100, 200) # wrong myfun(100, k=200) # k forces the use of named keywords to pass arguments myfun(100, **{'k': 200}) # dictionary keyword parameter
Double asterisk dictionary parameter:
Syntax:def function name (**dictionary parameter name)
statement block
function:
collect redundant keywords to pass parameters
Note:
dictionary parameter name is usually called "kwargs"
Example:
#! /usr/bin/python3 # This example shows the usage of the double asterisk dictionary parameter def func(**kwargs): print('The number of keyword arguments is:', len(kwargs)) print('kwargs =', kwargs) func (name = 'tarena', age = 15) # operation result: # The number of keyword arguments is: 2 # kwargs = {'name': 'tarena', 'age': 15} func(a=1, b='BBBB', c=[2, 3, 4], d=True) # operation result: # The number of keyword arguments is: 4 # kwargs = {'a': 1, 'b': 'BBBB', 'c': [2, 3, 4], 'd': True}
Function parameter description:
Positional parameters, default parameters, asterisk tuple parameters, named keyword parameters, double asterisk dictionary parameters can be mixedThe order of function parameters from left to right is:
1. Position parameter
2. Asterisk tuple parameter
3. Named keyword parameters
4. Double asterisk dictionary parameter
Example:def fn(a, b, *args, c, **kwargs):
pass
fn(100, 200, 300, 400, *'AB', **{'d':'D'}, c=100 )
#! /usr/bin/python3 def fn(a, b, *args, c, **kwargs): print('a=', a) print('b=', b) print('args=', args) print('c=', c) print('kwargs=', kwargs) fn(100, 200, 300, 400, *'AB', **{'d': 'D'}, c=100) ''' the result above a= 100 b= 200 args= (300, 400, 'A', 'B') c= 100 kwargs= {'d': 'D'} '''
Functions that can accept arbitrary positional and keyword arguments:
def fn(*args, **kwargs):pass
#! /usr/bin/python3 def fn(*args, **kwargs): print('args=', args) print('kwargs=', kwargs) fn() ''' args= () kwargs= {} ''' fn (a = 100) ''' args= () kwargs = {'a': 100} ''' fn ('a', a = 100) ''' args= ('a',) kwargs = {'a': 100}