Python Basics - super detailed introduction to the parameters of functions

Today's test

1,Write code to realize function tail -f access.log
    f.seek()

    Application (file object)/File handle (1)     Application (file object)/File handle (2)
    Operating system (real file) a.txt z
    Hard disk (computer space)

2,Two ways to modify code display files
    Mode 1:
    with open('source file',mode='r') as src_f:
        res=src_f.read()
        new_res=modify res

    with open('source file',mode='w') as dst_f:
        dst.write(new_res)


   Mode 2:
   with open('source file',mode='r') as src_f,open('Temporary documents',mode='w') as dst_f:
        for line in src_f:
            new_line=modify line
            dst.write(new_line)

   Delete source file
   Rename the temporary file to the name of the source file


3,What is the syntax for defining functions?
    function-->A container for functions (a pile of code)

    Built in functions: python The explanation has been defined and can be called directly
        open()
        input()
    Custom functions:
        Define first
        Post call

    def Function name(Parameter 1,Parameter 2,...):
        """Documentation Comments """
        Code block
        return value

4,What are the basic principles for using functions?

5,Briefly describe what happened in the function definition phase and call phase
    Definition stage:
        1,Apply for memory space, store the function body code, and then bind the memory address to the function name
            Function name=Internal address of function
        2,Only syntax is detected and no code is executed

    Calling function: function name()
        1,Pass the function name first(Variable name)Find memory for function
        2,Parentheses trigger the operation of function body code

6,The code shows three forms of defining functions
    def func():
        pass
    func()

    def func(x,y):
        pass

    func(1,2)

    def func():
        pass

7,The code shows three forms of calling functions
    # Statement form: run only function
    func(1,2)
    func()

    # Expression form
    res=func(1,2)

    res=func(1,2)*10

    # Parameter incoming
    func(func(1,2),10)
8,return What are the three forms of return value?
    None:   No, return
            return
            return None

    A value:
        return value

    Multiple values
        return Value 1,Value 2,Value 3

    emphasize:
        return Is the sign of the end of the function. There can be more than one in the function return,But just execute one
        The entire function will end immediately and the return The value after is returned as the result of this run

Relationship between formal parameter and argument

1,During the call phase, the argument (variable value) is bound to the formal parameter (variable name)
2,This binding relationship can only be used in function bodies
3,The binding relationship between arguments and formal parameters takes effect when the function is called, and the binding relationship is released after the function is called

The argument is the value passed in, but the value can be in the following form
 Form I:
func(1, 2)

Form 2:
a = 1
b = 2
func(a, b)

Form 3:
func(int('1'), 2)
func(func1(1, 2,), func2(2, 3), 333)

Specific use of formal parameters and arguments

Location parameters

The parameters defined from left to right are called position parameters
 Positional parameter: In the function definition stage, the functions are defined directly from left to right"Variable name"
       Features: it must be transferred. One more can't be transferred, and one less can't be transferred

def func(x, y):
    print(x, y)

func(1, 2, 3)
func(1,)

Position argument

In the function call stage, the values passed in from left to right are characterized by one-to-one correspondence with formal parameters in order

func(1, 2)
func(2, 1)

Keyword parameters

Keyword argument: in the function call phase, according to key = value Value passed in as
 Features: pass values to a formal parameter by name, which can be completely without reference to the order

def func(x, y):
    print(x, y)


func(y=2, x=1)
func(1, 2)

1. The location argument must be placed before the keyword argument

func(1, y=2)
func(y=2, 1)

2. You cannot pass values repeatedly for the same parameter

func(1, y=2, x=3)
func(1, 2, x=3, y=4)

Default parameters

Default parameter: the parameter that has been assigned at the function definition stage is called the default parameter
 Features: it has been assigned in the definition stage, which means that it can be assigned without assignment in the call stage
def func(x, y=3):
    print(x, y)


# func(x=1)
func(x=1, y=44444)

def register(name, age, gender='male'):
    print(name, age, gender)

register('Three guns', 18)
register('Rocket Force', 19)
register('artillery', 19)
register('No gun', 19, 'female')

Attention during mixing

1. The position parameter must be to the left of the default parameter

def func(y=2, x):
    pass

2. The value of the default parameter is assigned in the function definition stage. To be precise, it is given the memory address of the value

Model 1:

m = 2
def func(x, y=m):  # Memory address of y = > 2
    print(x, y)
m=333
func(1) # Output 1 2 is not 1 333

Model 2:

m=[111111, ]
def func(x, y=m):  # Memory address of y = > [111111,]
    print(x, y) 

m.append(3333333)
func(1) #Output is 1 [111111, 3333333]

3. Although the default value can be specified as any data type, variable types are not recommended

The most ideal state of the function: the call of the function is only related to the function itself, not affected by the external code

m=[111111, ]

def func(x, y=m):
    print(x, y)

m.append(3333333)
m.append(444444)
m.append(5555)


func(1)
func(2)
func(3)


def func(x, y, z, l=None):
    if l is None:
        l=[]
    l.append(x)
    l.append(y)
    l.append(z)
    print(l)

func(1, 2, 3)
func(4, 5, 6)

new_l=[111, 222]
func(1, 2, 3, new_l)

Variable length parameters (i.e. * and * * usage)

Variable length means that the number of values (arguments) passed in is not fixed when calling a function
 The argument is used to assign a value to the formal parameter, so the overflow argument must have a corresponding formal parameter to receive

Variable length position parameter

1: Format: * the formal parameter name is used to receive the overflow position argument. The overflow position argument will be * saved into the format of meta group, and then assigned the formal parameter name immediately followed by * can be any name, but it is a convention that it should be args

def func(x, y, *z):  # z =(3,4,5,6)
    print(x, y, z)

func(1, 2, 3, 4, 5, 6)

def my_sum(*args):
    res=0
    for item in args:
        res += item
    return res

res=my_sum(1, 2, 3, 4,)
print(res)

*It can be used in arguments with \ *, and the values after \ * are scattered into position arguments

def func(x, y, z):
    print(x, y, z)

# func(*[11,22,33]) # func(11,22,33)
# func(*[11,22]) # func(11,22)

l=[11, 22, 33]
func(*l)

3: Both formal parameters and arguments have*

def func(x, y, *args):  # args=(3,4,5,6)
    print(x, y, args)

func(1, 2, [3, 4, 5, 6])
func(1, 2, *[3, 4, 5, 6])  # func(1,2,3,4,5,6)
func(*'hello')  # func('h','e','l','l','o')

Variable length keyword parameters

1: * * formal parameter name is used to receive the overflow keyword argument, * * will save the overflow keyword argument in dictionary format and assign it to the following formal parameter name * * can be followed by any name, but by convention, it should be kwargs

def func(x, y, **kwargs):
    print(x, y, kwargs)

func(1, y=2, a=1, b=2, c=3)

2: * * can be used in an argument (* * can only be followed by a dictionary), with * * in the argument. The values after * * are scattered into keyword arguments

def func(x, y, z):
    print(x, y, z)

func(*{'x': 1, 'y': 2, 'z': 3})  # func('x','y','z ') a * is scattered and the key is obtained
func(**{'x': 1, 'y': 2, 'z': 3})  # func(x=1,y=2,z=3)

error
func(**{'x': 1, 'y': 2, })  # func(x=1,y=2) one less
func(**{'x': 1, 'a': 2, 'z': 3})  # func(x=1,a=2,z=3) name mismatch

3: Both formal parameters and arguments have**

def func(x, y, **kwargs):
    print(x, y, kwargs)

func(y=222, x=111, a=333, b=444)
func(**{'y': 222, 'x': 111, 'a': 333, 'b': 4444})

Mixing * and * *: * args must precede * * kwargs

def func(x, *args, **kwargs):
    print(args)
    print(kwargs)

func(1, 2, 3, 4, 5, 6, 7, 8, x=1, y=2, z=3)


def index(x, y, z):
    print('index=>>> ', x, y, z)

def wrapper(*args, **kwargs):  # args=(1,) kwargs={'z':3,'y':2}
    index(*args, **kwargs)
    # index(*(1,),**{'z':3,'y':2})
    # index(1,z=3,y=2)

wrapper(1, z=3, y=2)  # The parameters passed for wrapper are for index
 Analysis process: original format--->Summary----->Return to the original shape

task

1,Write function, the user passes in the modified file name and the content to be modified, executes the function, and completes the batch modification operation
2,Write a function to calculate the number, letter and space in the incoming string] And the number of [Others]

3,Write a function to judge whether the length of the object (string, list, tuple) passed in by the user is greater than 5.

4,Write a function to check the length of the incoming list. If it is greater than 2, only the contents of the first two lengths will be retained and the new contents will be returned to the caller.

5,Write function, check and obtain all the elements corresponding to the odd index of the incoming list or tuple object, and return it to the caller as a new list.

6,Write a function and check every word in the dictionary value Length of,If greater than 2, only the first two lengths of content are retained and the new content is returned to the caller.
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:Dictionary value Can only be string or list

# Homework: same as yesterday

Keywords: Python Back-end

Added by cavolks on Thu, 24 Feb 2022 13:16:43 +0200