function
Definition: A piece of code with a specific function
Advantages:
Solve repetitive writing problems in code
Can separate the implementation of the function and the user, improve the development efficiency
Increased portability of code
Classification:
Library functions: Print, input, ABS, etc.
Custom: User-encapsulated functions
Format:
function name ([ parameter list]):
function body
[] means optional, parameters can be either not, or there can be more than one.
Name of function:
Function call:
Example:
# no parameter no return value
DefPrint_hello ():
Print' Hello ')
?
# Print_hello ()
?
# no return value with parameter
DefPrint_n_hello (N):
ForIInchRangeN):
print ( ' Hello ')
?
# Print_n_hello (5)
?
# with parameter return value
def add (a, b):
c = a + b
# return result
return c
print (add (3, 5))
function parameters
Formal parameters: Parameters at the function definition
Arguments: Actual arguments, parameters at function calls
Mandatory arguments: Also called positional parameters, the function defined above is used in the required arguments, and the invocation must be in the same form as the definition.
Default parameter: is the parameter with default value, must be placed in the last
Variable-length parameters: When a function call passes a required parameter, more arguments are saved in args and Kwargs
DefShowAb=' Default value '):
# A is a must-pass parameter
PrintA
# b is the default parameter, which is the parameter with the default value, must be placed in the last
Printb
?
# Show (1, 2)
# keyword parameter, the time to pass the parameter specified the name, the order does not matter
# Show (b=456, a=123)
?
DefVar_len_args (ABName=' Default name ',*Args**Kwargs):
print (a)
Print (b)
print ( name)
# args is a tuple used to hold all the extra positional parameters
print (args)
# Kwargs is a dictionary, Used to store all the extra default parameters
print (kwargs)
?
var_len_args (1, 2, 3, 4, age=18)
DefShowAb):
PrintAb
?
L = [1,2]
# slightly verbose
# Show (L[0], l[1])
# Streamlined approach
Show*L
?
?
def show2 (a= ' AA ', b= ' BB '):
print (a, b)
?
d = { ' a ': ' Apple ', ' B ': ' banana '}
?
# show2 (a=d[' a '], b=d[' B '])
# A simple way to write the above method
show2 (** d)
Practice:
All of the previous exercises can be encapsulated into functions using functions.
Encapsulation functions: Generate random strings, Parameters: Length (default = 4), type (default = 0)
Try to find and learn a variety of data type-related functions
Python function basics