Today's content is detailed
1. What is a function
If you are a repairman , You need to have the tools ready in advance Not when you receive a repair job Only when they arrive at the site can they temporarily make tools
Empathy , Function is equivalent to a tool with a certain function
2. Function function
Reduce code redundancy Increase code scalability and maintainability
Improve application modularity and code reuse
Reduce code duplication Easy to modify
Combined with the above, we can regard functions as tools with certain functions Define in advance So that it can be used repeatedly
The use of functions must follow a principle :
First define
After the call
- The syntax structure of a function
def Function name ( Parameters 1, Parameters 2,...)
''' Comments on functions '''
The body of the function
return Return value
1.def
Is the key to define a function
2. Function name
Consistent with the naming of variable names It's better to know the meaning of the name
3. Brackets
When defining a function, parentheses must be added after the function name
4. Parameters
Parameters can be written in parentheses defining functions ( The number is not fixed ) You can also not write parameters , It is used to receive data passed from the outside to the internal code of the function body
5. Comments on functions
Similar to the instructions It is used to receive the main function and specific usage of the function
6. Function body code
The core area of the whole function ( Logic code )
7.return Return value
The return value of the control function The return value is after the function is called See if there is any feedback If there is, you will get the return value If there is no result, you will not get the return value
- Function definition and call
Definition of function
def my_func():
pass
Function call
my_func()
1. Functions must be defined before they are used
The code that defines the function must be run before the code that calls the function
2. Define function use def keyword The calling function uses the function name in parentheses ( Additional parameters may need to be added )
3. The function only detects the code syntax of the function code body in the definition stage Do not execute the function code body
4. What exactly is a function name
The function name is bound to a memory address It stores the function body code
Want to run this code You need to call the function >>>: Parenthesized function name
notes : Parenthesized function names have the highest execution priority ( Except for the definition stage )
- Classification of functions
1. Built in functions
python The interpreter defines the function for you in advance Users can use len()
''' Built in functions can be called directly
But the built-in methods of data types ( function ) You must use data type points to call It is equivalent to some built-in methods unique to data types
'''
2. Custom function
2.1 Empty function Function body code uses pass displacement There is no function for the time being It is mainly used for early project construction Act as the main function
def func()
pass
2.2 Nonparametric functions Function definition stage is not filled in brackets Nonparametric functions can be called directly by adding parentheses to the function name
def func()
print(' Nonparametric functions ')
2.3 There are parametric functions In the function definition stage, fill in the parameters in brackets Parametric function calls require the function name to be bracketed and the data value
def func(name,height)
print(' Parametric parameter ')
func(' Old six ',175)
- The return value of the function
The return value is the result of calling the function not essential The way to get the return value of a function is fixed
There are ways to obtain If not, it will be received by default None
1. The function body code does not return keyword : Default return None
def func():
print(' No, return The result of the return value ')
info = func()
print() # None
2. The function body code has return keyword : Don't write in the back And back again None
def func():
print(' Yes return The result of the return value ')
return
info = func()
print(info) # None
3. The function body code has return keyword : return What does it say after Just go back to what
def func():
print(' Yes return The result of the return value , Followed by parameter results ')
return 666
info = func()
print(info) # 666
def func():
print(' Yes return The result of the return value , Followed by parameter results ')
name = 'joker'
return name
info = func()
print(info) # joekr
If it is a data value, it will directly return If it is a variable, you need to find the corresponding data value and return
4. The function body code has return Keyword, followed by multiple data values ( name ) commas : By default, it will be automatically organized into groups to return
def func()
return 11,22,33,44
info = func()
print(info) # (11,22,33,44)
def func()
return [11,22,33,44]
info = func()
print(info) # [11,22,33,44]
def func()
return[11,22,33,44],{'name' = 'joker'},123
info = func()
print(info) # ([11,22,33,44],{'name' = 'joker'},123)
5. When the function body code encounters return Keyword will immediately end the operation of the function body code
def func()
print(' Hey, hey, hey ')
return 666
print(' Guess if I can run ')
func() # Hey, hey, hey
- The parameters of the function
There are two main types of parameters
1. Formal parameters
Function parameters filled in parentheses during the definition phase Referred to as ' Shape parameter '
2. Actual super parameter
Parameters filled in parentheses during the call phase of the function Referred to as ' Actual parameters '
def func(info): # info Namely func Formal parameters of
pass
def func(info): # 111 Namely func Actual parameters of
pass
function(111)
- Relationship between formal parameter and actual parameter
Formal parameters are equivalent to variable names , The argument is equivalent to the data value , During the function call phase, formal parameters will be temporarily bound with actual parameters , After the function body code runs , Dissolve the relationship immediately
def func(info): # Dynamic binding
print(info)
func(111) # 111
func('joker') # joker
func('666') # 666
func([1, 2, 3, 4, 5]) # 1, 2, 3, 4, 5
When the function is in the definition stage , Shape parameter info In a free state , When a function calls an argument , Formal parameters will be temporarily bound with actual parameters , After the function body code runs , Unbind formal parameters and arguments , Then wait for the next call , Binding is in progress , Get data values , And so on , Formal parameters can be bound to any data value , It outputs whatever it gives !
1. Position parameter , In the function definition stage, the variable names filled in brackets from left to right , It's called a positional parameter
When transferring values to position parameters, the number must correspond one by one , No more, no less
def func(name, age): # name, age It's the position parameter
pass
2. Location parameter , In the function call phase, the data values filled in brackets from left to right , It's called a positional argument
The actual parameter can be the data value , It can also be a variable name
def func(name,age,sex):
print(name,age,sex)
register(name='egon',sex='male',age=18) # You can transfer values by position
1. The formal parameters filled in the form of what is equal to what in the brackets in the function definition stage are called default value formal parameters
2. Bind values to formal parameters in the function definition stage The subsequent call stage can not transmit
3. The default is used in the call phase without transferring values Just pass it on
4. We also need to follow the rules summarized above ( The short one is in front Long in the back )
def func(name,age,gender='male')
print(f"""
name:{name}
age={age}
gender{gender}
""")
func('jason',18)
func('joker',20)
func('lisa',21,'female')
# name: jason
# age: 18
# gender: male
# name: joker
# age: 20
# gender: male
# name: lisa
# age: 21
# gender: famale
- Variable length parameters
If we call a function , If too many arguments are passed , There will be errors , But we can use (*+ The name of the parameter ) perhaps (** The name of the parameter ) To accept too many arguments
In principle, the formal parameter name can be any name , But the conventional gentleman's agreement is usually (*args) and (**kwargs)
1.*args. Used to accept location arguments . The extra arguments will be saved into Yuanzu .
2.**kwargs Used to accept keyword parameters The extra arguments will be saved into a dictionary .
Of course , When used inside a function , It doesn't have an asterisk .
Be sure to put it after the default parameter when defining .*args stay **kwargs Before
# *args Use
def func(x,y,*args):
print(x,y,args)
func(1,2,3,4,5,6) # 1 2 (3,4,5,6)
# **kwargs Use
def func(x,y,**kwargs):
print(x,y,kwargs)
func(1,2,a=3,c=4) # 1 2 {"a":3,"c":4}