Chapter 6 function

1. General

Code snippets that are well organized and realize a single function or related linkage

Programs that do not use functions} programs that use functions

Clear structure and simplified code

Advantages of functional programming:

(1) Modularization of the program not only reduces redundant code, but also makes the program structure clearer

(2) Improve the programming efficiency of developers

(3) It is convenient for later maintenance and expansion

2. Definitions

def()

def Function name([parameter list]);
    ["""Document string"""]
    Function body
    [return sentence]

Nonparametric function:
def add():
    result = 11 + 22
    print(result)
Parametric function:
def add_modify(a, b):
    result = a + b
    print(result)

3. Call

Function name ([parameter list])

add()
add_modify(10, 20)

1. The program pauses at the place where the function is called.

2. Pass data to function parameters.

3. Execute the statements in the function body.

4. The procedure returns to the place where it was suspended to continue.

Nested Call

def add_modify(a, b):
    result = a + b
    add()   	
    print(result)
add_modify(10, 20)

 

Inner nesting defines another function. At this time, the nested function is called outer function, and the nested function is called inner function

def add_modify(a, b):
    result = a + b
    print(result)
    def test(): 
        print("I'm an inner function")                  
add_modify(10, 20)
An inner function cannot be called directly outside a function
Inner functions can only be called indirectly through outer functions

4. Parameter transfer

The parameters set when defining a function are called formal parameters (formal parameters for short), and the parameters passed in when calling a function are called actual parameters (actual parameters for short). Parameter passing of a function refers to the process of passing actual parameters to formal parameters.

(1) Position transfer parameter

def get_max(a, b):
    if a > b:
        print(a,"Is a larger value!")
    else:
        print(b,"Is a larger value!")
get_max(8, 5)

(2) Keyword parameters

The format "formal parameter = argument" associates the real participating formal parameter

def connect(ip, port):
    print(f"equipment{ip}:{port}connect!")
connect(ip="127.0.0.1", port=8080)

Use the symbol "/" to restrict some formal parameters to receive only arguments that are passed by location

def func(a, b, /, c):
    print(a, b, c)
# Wrong calling method
# func(a=10, 20, 30)   
# func(10, b=20, 30)
# Correct calling method
func(10, 20, c=30)

(3) Default parameters

def connect(ip, port=8080): #definition
    print(f"equipment{ip}:{port}connect!")

connect(ip="127.0.0.1") #call
connect(ip="127.0.0.1", port=3306)

Equipment 127.0.0.1:8080 connect! #result
 Equipment 127.0.0.1:3306 connect!

(4) Pack

Add "*" or "* *" to formal parameters when defining functions:

"*" -- receive multiple values packaged in tuples

def test(*args): #definition
    print(args)

test(11, 22, 33, 44, 55) #call

(11, 22, 33, 44, 55) #result

"* *" -- receive multiple values packaged in dictionary form

def test(**kwargs): #definition
    print(kwargs)

test(a=11, b=22, c=33, d=44, e=55) #call

{'a': 11, 'b': 22, 'c': 33, 'd': 44, 'e': 55} #result

Although the formal parameters added with "*" or "* *" in the function can be any name conforming to the naming convention, it is recommended to use * args and * * kwargs here.

If the function does not receive any data, the parameters * args and * * kwargs are empty, that is, they are empty tuples or empty dictionaries

(5) Unpack

The argument is a tuple → can be split into multiple values with "*" → pass it to the formal parameter according to the positional parameter

The argument is a dictionary → it can be split into multiple key value pairs using "* *" → it is passed to the formal parameter according to the keyword parameter

def test(a, b, c, d, e):
    print(a, b, c, d, e)
nums = (11, 22, 33, 44, 55)
test(**nums)

{'a': 11, 'b': 22, 'c': 33, 'd': 44, 'e': 55} #result


def test(a, b, c, d, e):
    print(a, b, c, d, e)
nums = {"a":11, "b":22, "c":33, "d":44, "e":55}
test(*nums)

11 22 33 44 55 #result

(6) Mixed transfer

Priority is given to the way of passing by location parameters

Then pass it by keyword parameters

Then pass it by default parameters

Finally, it is delivered by packaging

When defining:

Parameters with default values must follow normal parameters.

The parameter identified with "*" must be after the parameter with default value.

Parameters identified with "* *" must follow parameters identified with "*"

def test(a, b, c=33, *args, **kwargs):
print(a, b, c, args, kwargs)
test(1, 2)
test(1, 2, 3)
test(1, 2, 3, 4)
test(1, 2, 3, 4, e=5)
1 2 33 () {}
1 2 3 () {}
1 2 3 (4,) {}
1 2 3 (4,) {'e': 5}

5. Return value

The return statement returns the data to the program at the end of the function, and returns the program to the location where the function is called to continue execution

def filter_sensitive_words(words):
    if "Shanzhai" in words:
        new_words = words.replace("Shanzhai", "**")
        return new_words
result = filter_sensitive_words("This mobile phone is a fake version!")
print(result)

This phone is**Version! #result

If multiple values are returned, they are saved to tuples

def move(x, y, step):
    nx = x + step
    ny = y - step
    return nx, ny     # Use the return statement to return multiple values
result = move(100, 100, 60)  	
print(result)

(160, 40) #result

6. Variable scope

The access permission depends on the location of the variable definition, and the valid range is called the scope of the variable

(1) Local variable

def test_one():
    number = 10      
    print(number)             # Access test_ Local variable number of one() function
def test_two():
    number = 20
    print(number)             # Access test_ Local variable number of two() function
test_one()
test_two()

10 
20 #result

(2) Global variable

number = 10         							# global variable
def test_one():
    print(number)   							# Function internal access to global variables
test_one()
print(number)       							# Function external access to global variables

10
10 #result

Only global variables can be accessed and cannot be modified directly

7.global and nonlocal keywords

(1)global

number = 10                    # Define global variables
def test_one():
    global number              # Use global to declare the variable number as a global variable
    number += 1
    print(number)
test_one()
print(number)

(2)nonlocal

def test():
    number = 10
    def test_in():
        nonlocal number
        number = 20
    test_in()
    print(number)
test()

8. Recursive function

Function called itself internally

(1) Basic conditions:

Recursive formula is the structure of solving the original problem or similar subproblem

The boundary condition is the subproblem of minimization and the condition of recursive termination

(2) Phase:

Recursion: recursion. This execution is based on the last operation result

Backtracking: when a termination condition is encountered, the value is returned level by level along the recursive back

def Function name([parameter list]): 
	if Boundary conditions:
		rerun result
	else:
		return Recursive formula

9. Anonymous function

Lambda < formal parameter list >: < expression >

difference:

(1) Ordinary has a name, anonymous has no name

(2) Ordinary contains multiple statements, and anonymity can only be one expression

(3) Ordinary can realize more complex functions, while anonymous can realize simpler functions

(4) Ordinary can be used by other programs, not anonymous

# Define an anonymous function and assign the function object it returns to the variable temp
temp = lambda x : pow(x, 2) 
temp(10) 

Keywords: linq p2p GNU

Added by ironman on Thu, 16 Dec 2021 15:00:11 +0200