1. Why use functions
#1. The organization structure of the code is not clear, and the readability is poor
. #2. When encountering duplicate functions, you can only write the implementation code repeatedly, and the code is redundant
. #3. When the function needs to be expanded, you need to find all the places where the function is implemented and modify it. , which cannot be managed uniformly and is extremely difficult to maintain
Second, the classification of functions
Built-in functions: In order to facilitate our development, some simple functions, the python interpreter has defined functions for us, that is, built-in functions. We can call built-in functions directly without having to define them in advance.
Commonly used built-in functions such as: len(), max(), sum(), etc.
Custom function: According to your own needs, you can customize a function to achieve a certain function. This is a custom function.
Three, the definition of the function
Definition of the function:
#Syntax def function name (parameter 1, parameter 2, parameter 3,...): ''' comment ''' function body return the returned value
The def keyword starts with the function name and parentheses () after the space, followed by a colon; the parameter name is filled in the parentheses, and no parameters are required
Fourth, the function call
1. Function call: function name()
2. Function calling principle: define first and then call
Five, the return value of the function
1. Do not write teturn
#function definition def mylen (): """ Calculate the length of s1 """ 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, str_len at this time is None print ( ' str_len : %s ' %str_len)
2. Just write return
3. There is the return keyword, which returns a value
4. With the return keyword, multiple values are returned
6. Parameters of the function
(1) Form participation in actual parameters
(2) From the perspective of formal parameters: positional parameters, keyword parameters, dynamic parameters
1. Positional parameters
2. Keyword arguments
3. Dynamic parameters
(3) Parameter sequence