[Python basics] Python functions

1, Function is the most used object in python.
Simple rules for function definition:

1. Defined in def, followed by function name, parameter and colon. Format:

2. The internal code block of the function needs to be indented

3. Use return to return the function value. The default return value is None

Format:

def function name (parameter):

Code block

return # is optional or can be used anywhere in the code block

2, Use of return in function:

return can be used anywhere in the function. Directly jump out of the current function and ignore other code blocks.

Return can also return None without parameters

You can also return None without a return

Return can also return dictionaries, lists, and functions (decorators are the returned function code blocks).

1. You can jump out if, while, for and other statements

def use_return():
    i = 0
    while True:
        i += 1
        for j in range(i):
            print(j, end='')
            
            if j == 5:
                return j
            
        print()

use_return() 

# Run result: when i is equal to 5, the function will be ended directly
"""
0
01
012
0123
01234
012345
"""

The above function changes the calling method:

print(use_return())            # The last line 0123455, the last 5 is the value of the return function, that is, the value of j. Try wrapping the last 5.

2. Call function:

Call the function using the function name and parentheses. What is called without parentheses is the function body, which is equivalent to an alias.

Use the example above
 Call 1
if use_return() == 5:
    print(5)

# Call 2
for i in range(0,use_return()):                
    print(i)
#Cannot be used because use_return() returns a number, but it is not a int type. It must be assigned to variables before calling variables.
v = use_return()
for i in range(0,v):                
    print(i)
    
# Call 3
s = use_return()
print(s)

# Calling function body
func = use_return
print(func)                        # Printed is use_return the memory address where the function is located
func()                             # Run use_return function

3, Relationship between function variables and external variables:

1. Mutable and immutable objects

strings, tuples, and numbers are immutable objects, while list,dict, etc. are modifiable objects.

2. Immutable type:

After the variable is assigned a=5, it is assigned a=10. Instead of changing the value of a, the variable is equivalent to a pointer, but the pointer has changed, and 5 itself has not changed. The 10 pointed to is a new address, rather than changing 5 to 10

Immutable types are passed into the function. After the function is modified, the value of external variables will not be affected.

3. Variable type:

The variable is assigned la=[1,2,3,4] and then la[2]=5. Although the memory address pointed to by la has not changed, the internal value has changed, so it is variable.

The variable type is passed into the function by la itself. Therefore, modifying la[2] inside the function also changes la[2] outside the function

def modify_la2(la_value):
    la_value[2] = 99999

la = [0, 1, 2, 3, 4, 5]
modify_la2(la)
print('la = %s' % la)
# Operation results
la = [0, 1, 99999, 3, 4, 5]

4. The function variable is searched from the innermost layer to the outer layer

def modify_la2():
    la[2] = 99999

la = [0, 1, 2, 3, 4, 5]
modify_la2()
print('la = %s' % la)
#modify_ If la2 cannot find the la, find the la outside the function. The la must be written in the modify of the call_ la2 () front

5, Parameter transfer form of function:

1. Required parameters: when calling a function, write the corresponding values in the order of variables
2. Keyword parameter: when calling a function, the variable name is used for assignment, and the variable = value

3. Default parameter: when defining a function, the parameter has a value. Def user (name, age = 20):, age = 20 is the default parameter

4. Variable length parameters:

(* args) indefinite length parameter. Only necessary parameters can be received, and the parameters can be converted into list storage

(* * kwargs) indefinite length parameter. It can only receive keyword parameters and convert the parameters into dictionary storage

5. Order in which parameters exist:

Required parameter, default parameter, args, *kwargs

def modify_la2(name, age=20, args, *kwargs):

The age default parameter does not work and must be assigned.

def modify_la2(name, age=20, *args, **kwargs):
    print('name=', name)
    print('age=', age)
    print('args=', args)
    print('kwargs=', kwargs)

modify_la2('dage', 'men',175, skill='pain', father='Adw')
# Operation results
name= dage
age= men
args= (175,)
kwargs= {'father': 'Adw', 'skill': 'pain'}

6, Anonymous function lambda

The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.

lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.

Format:

lambda [arg1 [,arg2,.....argn]]:expression

#Trapezoidal area formula:
resault = lambda x1, x2, h: (x1 + x2)*h/2

print(resault(1, 2, 4))

7, Summary:

A function is a collection of code that completes a function.
Like variable names, function names refer to the address of memory, and the memory storage pointed to is the code of the function.
The function name () is the result returned by calling the function; Only the function name has no parentheses, and the function itself is called.

If return is not defined, None is returned by default.
Define a function as a function and call it repeatedly to reduce the amount of code.
Defining functions can also achieve the effect of batch modification. Only functions are modified, and all calls are changed.
Function is the most used object in python.

Keywords: Python AI crawler

Added by tymlls05 on Mon, 13 Dec 2021 09:43:10 +0200