Python learning notes 3

Posted by Jaguar on Thu, 27 Jan 2022 09:25:21 +0100

8 function

The code that needs to be executed repeatedly in the program is generally encapsulated as a function.

8.1 defining functions

The syntax format of the custom function is as follows:

def Function name (formal parameter list):
    Function body
    return Return value

The example code is as follows:

# -*- coding: utf-8 -*-

def rect_area(width,height):
    area = width * height
    return area
def print_area(width,height):
    area = width * height
    print("{0} * {1} Area of rectangle:{2}".format(width,height,area))

8.2 calling functions

There are generally two ways to call functions.

8.2.1 calling function of position parameter

# -*- coding: utf-8 -*-

def rect_area(width,height):
    area = width * height
    return area
def print_area(width,height):
    area = width * height
    print("{0} * {1} Area of rectangle:{2}".format(width,height,area))
    
area = rect_area(1, 1)
print(area)

8.2.2 keyword calling function 8.3

# -*- coding: utf-8 -*-

def rect_area(width,height):
    area = width * height
    return area
def print_area(width,height):
    area = width * height
    print("{0} * {1} Area of rectangle:{2}".format(width,height,area))
    
area = rect_area(width = 1, height = 1)
print(area)

8.3 default values of parameters

Python does not have the concept of function overloading, but provides default values for function parameters.

def make_coffee(name="Cappuccino"):
    return "Make a cup{0}Coffee.".format(name)

coffee1 = make_coffee("Latte")
coffee2 = make_coffee()

print(coffee1) # Make a latte
print(coffee2) # Make a cup of cappuccino

8.4 variable parameters

Functions in Python can be defined to accept an indefinite number of parameters, which are called variable parameters. There are two kinds of variable parameters, that is, add * or * * before the parameter.

8.4.1 tuple based variable parameters (* variable parameters)

* variable parameters are assembled into a tuple in the function.

The example code is as follows:

# -*- coding: utf-8 -*-

def sum(*numbers):
    total = 0.0
    for number in numbers:
        total += number
    return total

print(sum(100.0,10.0,30.0)) # Output 150.0
print(sum(30.0,80.0)) # Output 110.0

8.4.2 dictionary based variable parameters (* * variable parameters)

* * variable parameters are assembled into a dictionary in the function.

The example code is as follows:

# -*- coding: utf-8 -*-

def show_info(**info):
    print('-----show_info------')
    for key, value in info.items():
        print('{0} : {1}'.format(key, value))
        
show_info(name='Tony', age=18, sex=True)
show_info(student_name='Tony',student_no='1000')

8.5 scope of variables in function

Variables can be created in the module. The scope (the effective range of variables) is the whole module, which is called global variables. Variables can also be created in functions. By default, the scope is the entire function, which is called a local variable.

# -*- coding: utf-8 -*-

x = 20

def print_value():
    x = 10
    print("In function x = {0}".format(x))
    
print_value()
print("global variable x = {0}".format(x))

We can promote local variables to global variables:

# -*- coding: utf-8 -*-

x = 20

def print_value():
    global x
    print("In function x = {0}".format(x))
    
print_value()
print("global variable x = {0}".format(x))

8.6 function type

Any function in Python has a data type. This data type is function, which is called function type.

8.6.1 understanding function types

The data of function type is the same as other types of data. Any type of data can be used as the return value of function and as function parameters. Therefore, a function can be used as the return value of another function or as a parameter of another function.  

# -*- coding: utf-8 -*-

# Define addition function
def add(a, b):
    return a + b

# Define subtraction function
def sub(a,b):
    return a - b

# Define calculation function
def calc(opr):
    if opr == '+':
        return add
    else:
        return sub
    
f1 = calc('+') # f1 is actually the add function
f2 = calc('-') # f2 is actually a sub function
print("10 + 5 = {0}".format(f1(10,5)))
print("10 - 5 = {0}".format(f2(10,5)))

If the number of parameters in the function parameter list is different, it is not a function of the same type.

8.6.2 filter function ()

Some functions for data processing are defined in Python, such as filter() and map(). Let's first introduce the filter() function.

The filter() function is used to filter the elements in the container. The syntax is as follows:

filter(function,iterable)

The parameter function is a function that provides filter conditions and returns Boolean values. The parameter iterable is the data of the container type.

When calling the filter() function, iterable will be traversed, and its elements will be passed into the function () function one by one. If the function() function returns true, the element is reserved; If False is returned, the element is filtered. Finally, the traversal is completed, and the reserved elements are put into a new container data.

The example code is as follows:

# -*- coding: utf-8 -*-

#Provide filter condition function
def f1(x):
    return x > 50 # Find elements greater than 50

data1 = [66,15,91,28,32,32,132,67,11,32]
filtered = filter(f1, data1)
data2 = list(filtered) # Convert to list
print(data2)

Note: the return value of the filter() function is not a list. If you need to return data of list type, you also need to convert it through the list() function.

8.6.3 mapping function (map)

The map() function is used to map (or transform) the elements in the container. The syntax is as follows:

map(function,iterable)

The parameter function is a function that provides transformation rules and returns the elements after transformation. The parameter iterable is the data of the container type. When the map() function is called, iterable will be traversed, and its elements will be passed into the function() function one by one, and the elements will be transformed in the function() function.

# -*- coding: utf-8 -*-

# Functions that provide transformation rules
def f1(x):
    return x * 2 # Transform rule multiplied by 2

data1 = [21,512,33,53,52,61,56]
mapped = map(f1,data1)
data2 = list(mapped) # Convert to list
print(data2)

8.7 lambda() function

Use the lambda keyword to define anonymous functions in Python. The function defined by lambda keyword is also called lambda() function. The syntax of defining lambda() function is as follows:

 

lambda parameter list:lambda body

Note: the body part of a lambda cannot be a code block or contain multiple statements. There can only be one statement. The statement calculates a result and returns it to the lambda() function. However, unlike the named function, it does not need to use the return statement to return.

The lambda() function, like the function with name, is a function type, so you can modify the above code. An example is as follows:

# -*- coding: utf-8 -*-

# Functions that provide transformation rules
def calc(opr):
    if opr == '+':
        return lambda a, b: (a + b) # Replace the add() function
    else:
        return lambda a, b:(a - b) # Substitute sub() function

f1 = calc('+')
f2 = calc('-')
print("10 + 5 = {0}".format(f1(10, 5)))
print("10 - 5 = {0}".format(f2(10, 5)))

8.8 using lambda() function

# -*- coding: utf-8 -*-

data1 = [66,15,91,28,98,50,7,80,99]

filtered = filter(lambda x: (x > 50),data1)
data2 = list(filtered)
print(data2)

mapped = map (lambda x: (x * 2), data1)
data3 = list(mapped)
print(data3)

Topics: Python Back-end