Python learning road - function

1. Initial function

How did we implement a piece of code before there were no functions? We learned the len() method before, and we can find the length of a list. If there is no len() method, then we have to write a similar function code to find the length of a list.

code show as below:

list = [1,2,3,'hello','abc']

count = 0

for i in list:

  count +=1

print (count)

This code implements the function of len(), but if there are more than n places in a program that need to test the length, we need to paste such code n times, so what are the disadvantages of this operation?

1. A lot of repetitive code

2. Poor readability

2. Create a function

We can solve the above two problems by defining a function.

s1 = 'hello world!!!!' 
def my_len():
count = 0
for i in s1:
count += 1
# print(count)

my_len()

2.1 The syntax of the function :
def functionname(parameter1,parameter2,parameter3,...):
    '''Comment'''
    function body
    return return value
Note: The function name must be able to express the function and meaning of the function 

2.2 How to run a function

The function name plus parentheses () to call a function is to execute the function

my_len()
2.3 Principles of function operation
: define first, then call
  1. function name, which is a variable name
  2. Variables must be defined first and then referenced, so if a function is not defined, but directly referencing this function is equivalent to referencing a variable name that does not exist
  3. In the function body, do not use the print() method, but use the return return value instead. The purpose is to let the function complete the minimum function and prevent the function from doing additional operations.
2.4 Function return value return
Function 1: Function of return value: When the function is executed, when the return value return is encountered, the function
code ends:
def func1(): 
print(11)
print(22)
return
print(333)
print(444)
func1()

function 2: The return value will be returned to the caller (executor) of the function
  • The code part of the function body can not write return, then the return value defaults to None
  • The return value is written as return None, then the return value is None
  • return followed by a single value
  • return followed by multiple values, multiple values ​​will be returned to the caller of the function in a tuple
Example: return followed by a single value
def my_len(): 
count = 0
for i in s1:
count += 1
return 666
print(my_len(),type(my_len()))

Example: return followed by multiple values
def my_len(): 
count = 0
for i in s1:
count += 1
return 666,222,count,'China'
print(my_len(),type(my_len()))

Example: return is followed by multiple values ​​and assigned to multiple variables
def my_len(): 
count = 0
for i in s1:
count += 1
return 666,222,count
ret1,ret2,ret3 = my_len() # (666, 222, 19,)
print(ret1)
print(ret2)
print(ret3 )

3. Function parameters
The parentheses when defining a function are where the function parameters are placed. At this time, the parameters are called formal parameters, referred to as formal parameters, for example: def my_len(a,b) #The parentheses are where the parameters are defined.
If the function is defined Sometimes there are formal parameters, and parameters should also be written in parentheses when calling a function. These parameters are called actual parameters, referred to as actual parameters, for example: my_len (1,2) #The actual parameters in the parentheses are the actual numbers

3.1 Types of actual parameters
  1. Positional parameter
    requirements: The parameters must be passed in order, and must correspond one-to-one
    Example:
    def func1(x,y): 
    print(x,y)
    func1(1, 2)
  2. Keyword parameter
    requirements: regardless of order, must correspond one by one
    Example:
    def func1(x,y,z):
    print(x,y,z)
    func1(y=2,x=1,z=5,)
  3. Mixed parameters (positional parameters + keyword parameters)
    requirements: The keyword parameters must be after the positional parameters, and must be in one-to-one correspondence
    Example:
    def func2(argv1,argv2,argv3):
    print(argv1)
    print(argv2)
    print(argv3)
    func2(1,2,argv3=4)

3.2 Types of formal parameters

  1. Positional parameter
    requirements: The parameters must be passed in order, and must correspond one-to-one
    Example:
    def func1(x,y): 
    print(x,y)
    func1(1,2)
  2. Default parameter
    requirements: must be placed after positional parameters
    Note:

    If there is a formal parameter with a default parameter, the actual parameter can be omitted when passing the parameter, and the function will automatically recognize the value of the default parameter when it runs.

    If an actual parameter passes a new value for the default parameter of the formal parameter, the new value overrides the value of the default parameter

    Example: Statistical name
    def register(name,sex='male'): 
    with open('register',encoding='utf-8',mode='a') as f1:
    f1.write('{} {}\n'.format (name,sex))

    while True:
    username = input('Please enter your name: /q or Q to exit') #You can pass no sex
    if username.upper() == 'Q':break
    if 'a' in username:
    sex = input('Please enter gender:') #Reassign the sex parameter while the program is running
    register(username,sex)
    else:
    register(username)
  3. Dynamic parameter (universal parameter)
    format:
    def my_len(*args, **kwargs)
    Function:
    In some cases, the number of actual parameters passed is not fixed. In order to ensure the operation of the program, the formal parameters need to be able to receive redundant Arguments

    *args in the formal parameter, the function is to receive all the redundant positional parameters of the actual parameter angle and put them into a tuple

    **kwargs in the formal parameter, the function is to receive all the redundant keyword parameters of the actual parameter angle and put them into a dictionary

    Example:
    def func2(*args,**kwargs): 
    print(args) # tuple (all positional arguments)
    print(kwargs) #dictionary (all keyword arguments)
    func2(1,2,3,4,5,6,7 ,11,'john','China',a='ww',b='qq',c='222')

4. Order of parameters
  1. Positional parameters-*args-default parameter
    example:
    def func3(a,b,*args,sex='男'):
    print(a)
    print(b)
    print(sex)
    print(args)
    func3(1,2,'中国','tom','jerry',sex='女')
  2. Positional parameters-*args-default parameters-**kwargs
    Example:
    def func3(a,b,*args,sex='男',**kwargs):
    print(a)
    print(b)
    print(sex)
    print(args)
    print(kwargs)
    func3(1,2,'中国','tom','jerry',name='jack',age=46)

5. Break up and aggregate functions
  1. Argument location: add * or ** is the sprinkler function
  2. Formal parameter position: add * or ** is
    an example of aggregation function:

    def func1(*args,**kwargs): # Definition of function* aggregation.

 

      print(args) 
  print(kwargs)

   l1 = [1,2,3,4]
   l11 = (1,2,3,4)
   l2 = ['tom','jack',4]
   func1(*l1,*l2 ,*l11) # Function execution: * Break up function.

 

 

 








 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325240378&siteId=291194637