Catalog
Function function
Simple rules for defining a function
Definition of function
Comments on functions
Function call
The return value of the function
1. Shape parameter
2. Actual parameters
1、 Positional arguments
From the perspective of actual parameters
1、 Pass values according to position ( involve if The ternary expression of )
2、 Pass value by keyword
3、 Location 、 Mixed use of keyword forms
From the angle of formal parameters
1、 The position parameter must pass the value
2、 Default parameters
1、 The concept of default parameters
2、 Default parameter trap problem ( Super focus )
3、 Dynamic parameters
The concept of dynamic parameters
*args Summation function application
**kwargs application
- 1. Make the program shorter and clearer
- 2. It's good for program maintenance
- 3. Can improve the efficiency of program development
- 4. Improved code reuse ( reusability )
Definition of function
def Key words start with , Space followed by function name and parentheses (), And finally, there's another one ":".
- Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters .
- The first line of the function optionally uses the document string — Used to store function descriptions .
- The function content is colon : start , And indent .
- return [ expression ] End function , Optionally return a value to the caller , Without expression return It's equivalent to returning to None.
def func(): print('hello world')
Comments on functions
- notes : Each function should have a corresponding description of the function and parameters , It should be written in the first line below the function . To enhance code readability .
>>>def func(): >>> ''' >>> This is an output hello world Function of >>> :return: >>> ''' >>> print('hello world')
Function call
Use the function name with parentheses to call How to write it : Function name () , At this time, the function of the function will be executed
Only the interpreter reads the function name () when , To execute this function , Without this instruction , Even if there is 10 Ten thousand lines of code are not executed . And how many times do you write this instruction , The code in the function runs several times
>>>def func(): >>> print('hello world') >>>func() >>>func() hello world hello world
Three cases of return value :no return value
One 、 no return value ---- return None( Don't complain ) 1、 Don't write return # Function definition def mylen(): """ Calculation s1 The length of """ s1 = "hello world" length = 0 for i in s1: length = length+1 print(length) # Function call str_len = mylen() # Because there is no return value , At this time str_len by None print('str_len : %s'%str_len) Output results : 11 str_len : None
2、 Just write return: End the entire functiondef ret_demo(): print(111) return print(222) ret = ret_demo() print(ret) Output results : 111 None
3、return None ---- Not commonly useddef ret_demo(): print(111) return None print(222) ret = ret_demo() print(ret) Output results : 111
Two 、 Returns a value
1、return There should be a space between and the return value, and any data type can be returneddef f(): return {'k':'v'} print(f()) Output results : {'k':'v'}
2、 As long as you return, you can receive 3、 If there are more than one in a program return, Then the value executes the first : Because when a function encounters return It will end 3、 ... and 、 Return multiple values : You can receive multiple return values with multiple variables (return 1,2) But if you only use one variable to receive multiple return values, you will get a primitivedef f2(): return 1,2,3 print(f2()) Output results : (1,2,3)
reason : Why does it return (1,2,3)、 Instead of going back 1,2,3 Or others ?
>>> 1,2 #python Multiple values separated by commas are regarded as a tuple . (1, 2) >>> 1,2,3,4 (1, 2, 3, 4) >>> (1,2,3,4) (1, 2, 3, 4)
Sequence decompression extension
# Sequence decompression one >>> a,b,c,d = (1,2,3,4) >>> a 1 >>> b 2 >>> c 3 >>> d 4 # Sequence decompression II >>> a,_,_,d=(1,2,3,4) >>> a 1 >>> d 4 >>> a,*_=(1,2,3,4) >>> *_,d=(1,2,3,4) >>> a 1 >>> d 4 # It also applies to strings 、 list 、 Dictionaries 、 aggregate >>> a,b = {'name':'eva','age':18} >>> a 'name' >>> b 'age'
1. Shape parameter
Variables written in the position of function declaration are called parameters , A complete formality . To represent this function, you need xxx
2. Actual parameters
The value passed to the function when the function is called . Acanthopanax japonicus , The information passed to the function during actual execution . For functions xxx
The parameter passing of a function is the process by which the function passes the actual parameter to the formal parameter .
def my_sum(a): #a Is the formal parameter print(a) res = my_sum('hello') # At this time 'hello' Is the actual parameter print(res) Output results : hello None
1、 Pass values according to position ( involve if The ternary expression of )
def mymax(x,y): # here x=10,y=20 the_max = x if x > y else y return the_max ma = mymax(10,20) print(ma) Output results : 20
2、 Pass value by keyword
def mymax(x,y): # here x = 20,y = 10 print(x,y) the_max = x if x > y else y return the_max ma = mymax(y = 10,x = 20) print(ma) Output results : 20
3、 Location 、 Mixed use of keyword forms
def mymax(x,y): # here x = 10,y = 20 print(x,y) the_max = x if x > y else y return the_max ma = mymax(10,y = 20) print(ma)
Be careful :
1、 The positional parameter must precede the keyword parameter
2、 A parameter can only be assigned once
1、 The position parameter must pass the value
def mymax(x,y): # here x = 10,y = 20 print(x,y) the_max = x if x > y else y return the_max # call mymax Do not pass parameters ma = mymax() print(ma) Output results : TypeError: mymax() missing 2 required positional arguments: 'x' and 'y'
1、 The concept of default parameters
When you call a function , If no parameters are passed , Then the default parameters . In the following example, if no age Parameters , The default value is used :( Generally, the value with small transformation is set as the default parameter )
# Write function description def func( name, age = 18 ): " Print any incoming strings " print (" name : ", name," Age : ", age) # call printinfo function func( age=100, name="zhou" ) func( name="zhou" ) Output results : name : zhou Age : 100 name : zhou Age : 18
2、 Trap problem with default parameters ( Super focus )
Super important knowledge points in default parameters : Trap problem with default parameters ( When the default parameter is a variable data type, such as list , Dictionary, etc )
If the value of the default parameter is a variable data type , Then each time a function is called, if no value is passed, the data type resource will be shared
''' If the value of the default parameter is a variable data type Then each time a function is called, if no value is passed, the data type resource will be shared ''' #========== When the default parameter is a list ==================== def f(l = []): l.append(1) print(l) f() f() f([]) f() f() #========== When the default parameter is a dictionary ==================== def f2(l = {}): l['k'] = 'a' print(l) f2() # Cover f2() def f3(k,l = {}): l[k] = 'a' print(l) f3(1) f3(2) f3(3) Output results : [1] [1, 1] [1] [1, 1, 1] [1, 1, 1, 1] {'k': 'a'} {'k': 'a'} {1: 'a'} {1: 'a', 2: 'a'} {1: 'a', 2: 'a', 3: 'a'}
The concept of dynamic parameters
Dynamic parameters , It is also called variable long-range transmission parameter , You need to pass many parameters to the function , Indefinite number , In that case , You just ⽤*args,**kwargs receive ,args It is the form of Yuanzu , Receives all parameters except key value pairs ,kwargs Only the parameters of key value pairs are received , And keep it in the dictionary .
*args : It receives the value of parameters according to the position , Organize into a tuple
**kwargs: The value of the parameter passed by the keyword is accepted , Organize into a dictionary
args Must be in kwargs Before
def mysum(*args):
the_sum = 0
for i in args:
the_sum+=i
return the_sum
the_sum = mysum(1,2,3,4)
print(the_sum)
Output results :
10
def stu_info(**kwargs):
print(kwargs)
print(kwargs['name'],kwargs['sex'])
stu_info(name = 'lisa',sex = 'male')
dir = {'a':97,'b':98}
print(*dir)
Output results :
{'name': 'lisa', 'sex': 'male'}
lisa male
a b
From the perspective of arguments :
Pass the parameters according to the position
Pass parameters by keywords
Be careful : Two can be used together, but the parameters must be transferred according to the position first , Then pass parameters according to keywords , Because you cannot pass multiple values to the same variable
From the perspective of parameters :
Positional arguments : Must pass , And there are several parameters to pass a few values
Default parameters : Can not pass , If not, the default parameters are used , If it's passed, use itOnly when the function is called
According to the position : Write the value of the parameter directly
Pass by keyword : keyword = value
When defining a function :
Positional arguments : Define functions directly
Default parameters ( Key parameters ): Parameter name = ‘ Default value ’
Dynamic parameters : Any number of parameters can be accepted
Add... Before parameter name *, Custom parameter name args;
Add... Before parameter name **, Custom parameter name kwargs;
The order of the parameters ( Must be avoiding ): Positional arguments > *args > Default parameters > **kwargs
Finally, thank you for seeing here :
In an unpublished article, Lu Xun said :“ If you understand the code, you must operate it yourself, so that you can better understand and absorb .”
One last sentence : A man can succeed in anything he has unlimited enthusiasm , Let's make progress together