Do you really consider yourself proficient in Python? Take you to an article to find out the gaps and fill in the gaps, and feel how far you are from mastering Python.

  ​ Click me to get a full set of software testing (automated testing) video materials for free (note "csdn000")

 

1. Modular programming idea

Modular programming is the basic idea of ​​Python. If you are a beginner in Python, you should have used the turtle, random, and math modules. Before using modules, you need to import the modules, and then use them according to your own problem needs.

Python provides a large number of module libraries, some of which come with the Python language system, some are provided by third parties, and can also be created by developers as needed.

The built-in module can be used directly.

Third-party modules need to be installed using the installer pip that comes with Python (pip3 is an upgraded version of pip).

pip3 install 模块

pip or pip3 are command line programs. Before using it, you need to enter the command mode of the OS. In the Windows operating system, use win+r to open the run dialog box, enter cmd, and enter the command operation mode.

Directly enter pip3 in the command mode,  and the following basic functions of pip3 will appear   (premise that the Python runtime environment needs to be installed).

Commands:
  install                     安装模块
  download                    下载模块
  uninstall                   卸载模块
  list                        列表出安装的模块
  show                        显示安装模块的信息
  check                       验证模块的依赖信息
  config                      管理本地和全局配置
  search                      从 PyPI (Python Package Index 是 Python 编程语言的软件存储库) 搜索模块
  index                       使用模块的索引检查模块的合法性

What is modular programming?

A file in the Python language system is a module. A module can encapsulate many practical functional codes. These functional bodies can exist in the form of functions or in the form of classes. Modules are completely self-independent.

Modules can depend on each other as needed.

Modular programming can greatly improve the reusability of code, and can also infinitely expand the functionality of the Python language. After years of accumulation and precipitation, Python has many rich modules that can be used.

 

2. Function

In the Python language, functions are first-class citizens.

Function definition syntax structure :

def 函数名(函数参数):
	函数体
  • Defining a function, that is, creating a function, must use the  def  keyword.
  • The function name is the unique identifier of the function, and it is also the interface (entrance) of using the function.
  • Function parameters: used to receive data variables passed by the caller. Also known as formal parameters (placeholders). There can be none or more than one parameter.
  • Function body: The function implementation provided by the function.

Features of Python functions:

Python  is both an object-oriented programming language and a function-oriented programming language. Functions can be used as parameters of other functions, and can also be used as return values ​​of other functions. A function is essentially a data type .

def han_shu():
    print(1)
print(type(han_shu))
'''
输出结果:
<class 'function'>
'''

Sometimes, functions in a class are called methods. It's just a semantic difference, the essence is the same.

Creating a function means  creating a function  object based on the function  type  .

  1. function as parameter:
def a_han_shu(f):
    f()
def b_han_shu():
    print('Test')
# 函数作为参数不要有括号。    
a_han_shu(b_han_shu)
'''
输出结果
Test
'''
  1. Function as return value:
def a_han_shu():
    def b_han_shu():
        print('Test')
    return b_han_shu
# 返回的是对 b_han_shu 函数的引用
f=a_han_shu()
f()
'''
输出结果
Test
'''

A function cannot have parentheses, whether it takes a function as a parameter or returns a value.

When there are parentheses after the function, it means that the logic code in the function is executed.

  1. Use functions from other modules as arguments:
import turtle
def forward(f):
    f(200)
# turtle.forward 后面不能有括号
forward(turtle.forward)
'''
用自己的函数封装小海龟的前移函数
'''
  1. Class methods are essentially functions
class Dog:
    def __init__(self, name):
        self.name = name

    def run(self):
        print(self.name,"在 run……")

    def bark(self, f):
        f()
        print(self.name,"在 叫……")

d = Dog('小花')
d.bark(d.run)
'''
输出结果
小花 在 run……
小花 在 叫……
'''

The parameter form of the function:

  1. Positional passing parameters:
def han_shu(num1, num2):
    return num1 - num2

#如果想得到 10-4 相减的结果,调用时 10,4 的顺序不能颠倒。如果传递4,10 得到 4-10 结果
res = han_shu(10, 4)
print(res)
'''
输出结果
6
'''
  1. Named passing parameters:
def han_shu(num1, num2):
    return num1 - num2

#通过参数名传递数据
res = han_shu(num1=10,num2=4)
print(res)
# 传递参数时可以颠倒顺序
res = han_shu(num2=4,num1=10)
print(res)
'''
输出结果
6
'''
  1. Default value passed
def han_shu(num1, num2=4):
    return num1 - num2

#通过参数名传递数据
res = han_shu(10)
print(res)
'''
输出结果
6
'''

Remember: Default value parameters can only be placed last.

  1. variable length parameter
def han_shu(*num):
    return num
res = han_shu(10, 4,6,12)
print(res)
'''
输出结果
(10, 4, 6, 12)
'''

The * in front of the parameter indicates that 0, 1 or more parameters can be passed, and the function will put all the passed data in a tuple.

def han_shu(**num):
    return num
res = han_shu(a=1,b=2,c=3)
print(res)
'''
输出结果
{'a': 1, 'b': 2, 'c': 3}
'''

The ** in front of the parameter indicates that it can receive any number of parameters in the form of key and value pairs. The function internally stores the passed data in the form of a dictionary.

anonymous function

Anonymous functions, also known as  lambda  functions, are a simplification of function syntax. lambda  functions have the following characteristics:

  • There is no function name.
  • Can only be used once.
  • There can only be one function body.
  • There cannot be a return statement, and the calculation result of the only statement block is returned by default.
def han_shu():
    return lambda num: num + 1
res = han_shu()
print(res(12))
'''
输出结果
13
'''

The han_shu function above returns a reference to an anonymous function. Equivalent to the following code:

def han_shu():
    def f(num):
        return num + 1
    return f
res = han_shu()
print(res(12))
'''
输出结果
'''

  ​ Click me to get a full set of software testing (automated testing) video materials for free (note "csdn000")

Built-in functions:

 There are many built-in functions, or system functions, in Python . The characteristics of such functions are: they can be used directly.

Common built-in functions:

Function name function Remark
input([x]) Interactively get data entered by the user data is of type string
print(x) output the x value to the console When the output content is not specified, the output will wrap
pow(x,y) x raised to the y power, equivalent to x**y
round(x,[,n]) round x to n decimal places When n is not specified, no decimal places are preserved
max(x1,x2,x3,……) Returns the maximum value in the array
min(x1,x2,x3,……) Returns the minimum value in an array
sum(x1,x2,x3,……) Returns the sum of all numbers in the sequence The parameter needs to be an iterable type
len () Returns the length of container objects such as tuples, lists, sets, strings, etc.
range(start,end,step) returns an iterable object There are index(), and count() methods
eval(x) execute a string expression Can build dynamic expressions
int(x) Convert x to int type data x can be of type string or float
float(x) Convert x to float type data Can be of type int or str
str(x) convert x to str type
list(x) Convert an iterable object to a list
open() open a file
abs(x) returns the absolute value of x
type(x) returns the data type of x
word (x) Returns the unicode encoding of the string
chr(x) Returns the string corresponding to unicode
sorted(x) Sort operation
tuple(x) Convert iterable to tuple
set(x) Convert an iterable object to a collection

 

3. Recursive algorithm

Recursion is when a function calls itself. The recursive call has 2 procedures:

1. Progressive process: if there is a function a. Recursive calling process: the first call a ===> the second call a ===> the third call a => ...=> the nth call a. Without any abort conditions, it advances indefinitely, causing memory exhaustion. Therefore, recursion must have a terminal condition.

2. Backtracking process: The backtracking process is the reverse process of the progressive process. The characteristic of function call is that after a calls b, b must return to a after the end. In the recursive call process, when the nth call is completed, it will enter the n-1th time, and then enter the n-2th time...all the way back to the first call.

A function is a logical block, and a recursive process is the process of repeatedly executing a logical block within a function, so recursion can achieve the same effect as a loop syntax. In theory, the operations implemented by the loop syntax can be completely replaced by recursion, but the performance consumption of recursion is much greater than that of the loop syntax structure.

Use recursion only if it is not possible or cumbersome to implement using loop syntax constructs.

Recursion is suitable for solving a seemingly complicated problem, but the key point of its solution lies in a very sub-problem.

For example, to find the factorial of a number: Calculate 5! (factorial of 5).

  1. Progressive process: 5! =5X4! , if you find 4! then 5! It can also be found, and 4!=4X3!, the problem becomes to find 3! The factorial of , and 3!=3X2!, the problem becomes to find 2! , while 2! =2X1! , the problem becomes to find 1!, and 1! is 1. At this point the progressive process can be terminated.

  2. Backtracking process: return the result of 1! to 2! , and then put the obtained 2! The result is returned to seek 3! , then put 3! The result is returned to seek 4! , then put 4! The result is returned to 5! . Finally got the result.

def jc(num):
    # 递归终止
    if num == 1:
        return 1
    return num * jc(num - 1)
res = jc(5)
print(res)

For example, the recursive algorithm for finding the factorial of a certain number above belongs to linear progression and is relatively easy to understand.

Another example: the Fibonacci sequence.

1,1,2,3,5,8,13,21……

Starting from the third number, each number is the result of adding the previous two numbers (the number in the first and second position is 1). This problem conforms to the recursive scheme. If you want to know the number in the 5th position, you need to know what the number in the 3rd and 4th positions is. If you want to know the number in the 3rd position, you need to know the number in the 1st and 2nd positions. How much, if you want to know the 4th position, you need to know what the numbers are in the 2nd and 3rd positions. This progressive process is a tree structure.

Observing the progressive diagram, it is found that when finding the 5th position number, you need to know the 3rd position number, and to find the 4th position number, you also need to solve the 3rd position number. The numerical solution for the 3rd position is evaluated at least 2 times throughout the progression.

In the progressive process of the tree structure, it is a common problem to be repeatedly calculated. Generally, a caching mechanism is used, and the numbers that should be calculated are not calculated.

Regular recursive algorithm without caching:

def fb(pos):
    if pos==1 or pos==2:
        return 1
    return fb(pos-1)+fb(pos-2)
res=fb(5)
print(res)
'''
输出结果
5
'''

Algorithm using cache mechanism:

#缓存器,位置作键,此位置的数字为值
cache = {}
def fb(pos):
    if pos == 1 or pos == 2:
        return 1
	# 查看缓存中是否存在此位置已经计算出来的数字
    if cache.get(pos) is not None:
        return cache.get(pos)
    # 缓存中没有,才递进
    val = fb(pos - 2) + fb(pos - 1)
    #得到值别忘记缓存
    cache[pos] = val
    return val
res = fb(5)
print(res)
'''
输出结果
5
'''

The principle of the cache mechanism: when the number of a certain position is needed, it is first searched from the cache, and if it is not, it will continue to advance.

Another example: Yang Hui's triangle

The numerical law of Yang Hui's three solutions. The first and last columns of each row are 1, and the values ​​of the other columns of each row are equal to the sum of the numbers on its left and right shoulders.

Suppose now what is the number in row 5 and column 3? See how to compute recursively.

After observation, it can be seen that the number at the (3, 2) position is calculated twice, if the Yang Hui three solution is solved recursively. When the number of rows is larger, the more values ​​are repeatedly calculated, and the performance consumption is very serious.

To improve performance, use a caching mechanism whenever possible.

Regularly do not use the caching mechanism:

import time
cache = {}
def yh(row, col):
    if row == 1 or col == 1 or row == col:
        return 1
    return yh(row - 1, col - 1) + yh(row - 1, col - 2)
s = time.process_time()
res = yh(25, 5)
e = time.process_time()
print(res)
print('所使用的时间:',e - s)
'''
输出结果
5242885
所使用的时间: 1.671875
'''

Use cache mechanism:

import time
def yh(row, col):
    if row == 1 or col == 1 or row == col:
        return 1
    if cache.get((row, col)) is not None:
        return cache.get((row, col))
    val = yh(row - 1, col - 1) + yh(row - 1, col - 2)
    cache[(row, col)] = val
    return val

s = time.process_time()
res = yh(25, 5)
e = time.process_time()
print(res)
print("使用时间:",e - s)
'''
输出结果
5242885
使用时间: 0.0
'''

The difference in computation time between using the cache and not using the cache is obvious.

4. File Operations

Use open("filepath", "mode").

Modes are r readable and r+ readable and writable. The file must exist when opened in r mode,

w is writable, w+ is readable and writable, when opened in w mode, the file may not exist, if it exists, the content in the file will be cleared.

a is append-write, a+ append-write, and readable. When opened in a mode, the file may not exist, if it exists, the contents of the file will not be cleared.

How to read:

with open("d:/temp.txt","r") as f :
    # 读所有内容
    f.read()
    # 读一行
    f.readline()
    # 读出所有行
    f.readlines()

Write method:

with open("d:/temp.txt","w") as f :
    # 写入数据
    f.write(1)
    # 把列表数据写入
    f.writelines([1,2])
    # 使用 print 方法写入
    print(123,34,sep=",",file=f)

5. Summary

A brief summary of the knowledge that python needs to master.

  ​ Click me to get a full set of software testing (automated testing) video materials for free (note "csdn000")

Guess you like

Origin blog.csdn.net/csdnchengxi/article/details/123665111