Modular programming
Modular programming refers to the encapsulation of programs (function encapsulation, object-oriented, file...)
What is a function?
Function - > function, function
A function is a block of code with a specific function
Function?
Function is to encapsulate the code to improve the reusability of the code, improve the development efficiency, and reduce the later maintenance cost
Definition and use of functions
# Define function [basic structure] def Function name([parameter list]): The code of the specific function of the current function The code of the specific function of the current function . . . . # The function will not be executed after encapsulation, but the function is defined # If you want to use a defined function, you need to use syntax to call the function # Function call Function name()
Characteristics and precautions of function
- After the function is defined, it will not be called or executed
- Function cannot be called before function definition.
- The number of calls to a function is not affected
- The naming of functions should follow the naming convention
- Alphanumeric underscores cannot begin with numbers
- It is strictly case sensitive and cannot use keywords
- The naming should be meaningful and not in Chinese
- The function name should not conflict, and it will be overwritten after the conflict
About parameters of function
When a function is defined, formal parameters can be defined at the position of the parameter list
If the function has formal parameters, you also need to give parameters when calling the function
The process by which an argument passes a value to a formal parameter is essentially a variable assignment operation
(1) Concept and classification of function parameters
Function parameters:Data to be passed when calling. Function parameters are divided into formal parameters and arguments: . Formal parameter meaning: Parameters for function definition . Argument meaning: Parameters in function call Form reality relationship:Function call,The number of formal and actual parameters should correspond to each other one by one Type of formal parameter: General parameters,Default parameters,General collection parameters,Named keyword parameters,Keyword collection parameters Argument type: General argument,Keyword argument
(2) General parameters
(positional parameter) a common parameter that receives the value passed by the argument
(3) Default parameters:
Parameter with default value after normal parameter
Syntax: (x,y=2) y is the default parameter
(4) Collection parameters:
Specifically collect redundant arguments passed during function calls
1.General collection parameters:Designed to collect redundant common parameters,Form a new tuple grammar:Parameter preceded by* example:*args 2.Keyword collection parameters:Used to collect extra keyword arguments,Form a new dictionary grammar:Parameter preceded by** example:**kwargs
(5) Named keyword parameters
The parameter placed after the * sign when defining. When calling, the specified parameter name must be passed in to call
grammar:(a,*,x) x Is a named keyword parameter If there are already collection parameters in the function parameters, the parameters after the collection parameters are named keyword parameters grammar:(*args,x,y)
(6) Position order of formal parameter declaration:
Common parameters - > default parameters - > collection parameters - > named keyword parameters - > keyword collection parameters
def func(a,b,c=1,*args,d,**kw) a,b Is a normal parameter, c Is the default parameter, args Is to collect parameters, d Is a named keyword parameter, kw Is a keyword collection parameter It is rare for five parameters to occur at the same time def func(a,b=2,*,c,d,**kw) a Is a normal parameter, b Is the default parameter, c,d Is a named keyword parameter, kw Is a keyword collection parameter
Placement of all parameters
- Argument: ordinary argument comes first and keyword parameter comes last
- Formal parameters:
- Keyword collection parameters must appear at the end
- Collecting parameters is recommended after common parameters
- Recommended order: common formal parameters, collection parameters, keyword collection parameters
Function return value
A function can not only complete certain functions, but also return some contents as needed
The return keyword is used in the function to specify the return data. You can return any type of data
The return value of the function will return the data to the caller. You can use variables to receive or other processing
Functions can be divided into two categories 1. Execution process function: the function body can complete certain functions without return value 2. Function with return value: the function body completes certain functions and returns a result to the function call
return the characteristics of the returned value
- You can use return in the function to return data
- You can use return to return any content or data
- return returns the returned value to the function call
- Return means the end of the function. The code after return is not executed
- If return is not used in the function or there is nothing after return, None is returned by default
# Suppose there is such a requirement, define a function, complete the calculation of two numbers, and output the results # def jia(n1,n2): # res = n1+n2 # print(res) # jia(2,5) # Requirements change, define a function, complete the calculation of two numbers, and return the results def jia(n1,n2): res = n1+n2 return res r = jia(2,4) print(r)
Variable scope
The scope is the currently active and available scope area
Valid range of variable
Global variable: a variable that can be used inside and outside a function
Local variable: a variable that can be used inside a function
local variable Variables defined within a function, local variables, cannot be used outside a function global variable Use inside functions global Directly defined variables are global variables, which can be used inside and outside the function Variables defined outside the function are used inside the function global Keyword, then it is also a global variable globals() Get global data locals() Get data for the current scope Variables defined outside the function can be accessed by the function, but cannot be changed Classification of data types: Variable data type: a variable defined outside a function, which can be used in a function, Lists and dictionaries Immutable data type: variables defined outside the function can only be accessed inside the function, and other operations cannot be used
Not only variables but also functions have the same scope
def outer(): print('this is outer function...') # A function defined within a function is called a local function and cannot be used outside the function def inner(): print('this is inner function...') inner() outer() # inner()
nonlocal
How to use the local variables in the upper function in the inner function?
If you want to use the variables of the outer function in the inner function, you need to use the nonlocal keyword reference
Local variables defined in the function of the previous level can be referenced, but they cannot be promoted to global variables
# Define an outer function def outer(): # Local variables of external functions num = 10 # Inner function, local function, a function defined inside a function def inner(): # The nonlocal keyword is used in local functions, nonlocal num # Local variables defined in the function of the previous level can be referenced, but they cannot be promoted to global variables num += 1 print(num) inner() outer() # print(num)
Documentation on functions
def outer(): ''' Here are some documentation of the current function. You need to explain the function of the current function, If the current function has row parameters, you also need to describe the row parameters one by one name: This is a name Parameter, what is the function... age : This represents the current age :return: The return value of the current function is described here... ''' print(globals()) print(__name__) # Get the file name of the current script, print(__doc__) # Gets the documentation for the current script # print(outer.__doc__) # Gets the documentation for the current function ''' Magic variable __name__ ==> If the current script is the main program, the value is __main__,If it is used as a module and referenced in another script, the value is the name of the current file __doc__ ==> The document description of the current script. The first three quotation mark comment in the current script is the description document of the current script { '__name__': '__main__', '__doc__': '\n If you want to use the variable of the outer function in the inner function', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x110444350>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/yc/Desktop/code/8.nonlocal keyword.py', '__cached__': None, 'outer': <function outer at 0x1104938c0> } '''