The most comprehensive python explanation on the whole network, the impeccable "Remember to Collect"

The most comprehensive python explanation on the whole network, the impeccable "Remember to Collect"

table of Contents

1 Introduction

Let's briefly talk about the current market applications of Python:

  • Web and Internet development
  • Scientific calculations and statistics
  • artificial intelligence
  • Desktop interface development
  • Software development
  • Back-end development
    2. Network interface: It can facilitate system maintenance and management. It is one of the iconic languages ​​under Linux and is an ideal programming tool for many system administrators.

3. Graphics processing: It is supported by graphics libraries such as PIL and Tkinter, which can facilitate graphics processing.

4. Mathematics processing: NumPy extension provides a large number of interfaces with many standard math libraries.

5. Text processing: The re module provided by python can support regular expressions, as well as SGML and XML analysis modules. Many programmers use python to develop XML programs.

6. Database programming: Programmers can communicate with databases such as Microsoft SQL Server, Oracle, Sybase, DB2, MySQL, and SQLite through modules that follow the Python DB-API (application programming interface) specification. Python comes with a Gadfly module, which provides a complete SQL environment.

7. Network programming: Provides a wealth of modules to support sockets programming, enabling easy and rapid development of distributed applications. Many large-scale software development projects such as Zope, Mnet and BitTorrent. Google are using it extensively.

8. Web programming: application development language, supporting the latest XML technology.

9. Multimedia applications: Python's PyOpenGL module encapsulates the "OpenGL application programming interface", which can perform 2D and 3D image processing. The PyGame module can be used to write game software.

10. Pymo engine: PYMO is called python memories off. It is an AVG game engine running on Symbian S60V3, Symbian3, S60V5, Symbian3, and Android systems. Because it is developed based on the python2.0 platform and is suitable for creating memories off-style AVG games, it is named PYMO.

it has started! ! ! No nonsense

Insert picture description here

How to copy files in Pyhon

def main():
    f1 = input("Enter a source file name:").strip()
    f2 = input("Enter a destination file name:").strip()

    infile = open(f1, 'r')
    outfile = open(f2, 'w')

    count_lines = count_chars = 0
    for line in infile:
        count_lines += 1
        count_chars += len(line)

    print(count_lines, "lines and", count_chars, "chars copied")



Python math library and its application

Insert picture description here

 Random number library and its application

Insert picture description here

Python exception handling mechanism

Python uses try...except...else...finally to prevent the program from crashing due to operating errors. The exception capture mechanism can capture any type of error, such as entering a non-numerical type (NameError), entering an invalid expression (SyntaxError), etc. Only when there is no exception in the try statement, the else statement will be executed, and finally will be executed regardless of whether there is an exception:

	<body>except <ErrorType1>:
	<handler1>except <ErrorType2>:


1. Use synchronous assignment statements to exchange values ​​between x and y: x, y = y, x.

2. val=pow(2,1000), return the length value of the val result with one line of code: len(str(val)).

3. The priority of Boolean operators from high to low is: not, and, or.

4. The zero value of a number is considered false, and any non-zero value is true. For sequence types, an empty sequence is considered false, and a non-empty sequence is considered true.

5. Commonly used coding:

  • ASCII code is a standardized character set, using 7 binary bit codes to represent 128 characters.
  • Unicode is a cross-language, cross-platform, agreed and unique binary encoding, and each character is two bytes long.
  • UTF8 encoding, variable length Unicode, English corresponds to 1 byte, Chinese corresponds to 3 bytes.

6. The string type in python is not encoded, you can use encode() to encode and decode() to decode.

Insert picture description here

Common commands of turtle library

1. Turtle library takes the center of the screen as the origin of coordinates.

2.forward (distance) moves the arrow to a specified coordinate.

3.left(angle)/right(angle) rotate one angle to the left/right.

4. penup() lifts the pen to use when drawing in another place, paired with pendown().

5.goto (x, y)。



Use turtle library to draw five-pointed star

import turtle

p = turtle.Turtle()
p.begin_fill()for i in range(5):

Use turtle library to draw python

import turtle
def draw_snake(rad, angle, len, neckrad):
    for i in range(len):, angle), angle), angle, 2)
    turtle.fd(rad) + 1, 180)
    turtle.fd(rad * 2 / 3)
def main():
    turtle.setup(1300, 800, 0, 0)
    pythonsize = 30
    draw_snake(40, 80, 5, pythonsize / 2)


Data-driven dynamic path drawing

import turtle

def main():
    turtle.setup(800, 600, 0, 0)

    pen = turtle.Turtle()

    result = []
    file = open("a.txt", 'r')
    for line in file:
        result.append(list(map(float, line.split(','))))

    for i in range(len(result)):
        pen.color((result[i][3], result[i][4], result[i][5]))
        if result[i][1]:

    pen.goto(0, 0)

if __name__ == '__main__':

Use Monte Carlo method to estimate the value of Pi

from random import *from math import  *from time import *

DARTS = 1000000
hits = 0
clock()for i in range(1,DARTS):
    dist = sqrt(x**2+y**2)
    if(dist <= 1.0):
        hits = hits+1
pi = 4*(hits/DARTS)print("Pi的值是:%s"%pi)print("程序运行时间是 %-5.5ss"%clock())
for n in range(2,100):
    for x in range(2,n):
        if n % x == 0:
            print(n, "equals", x, "*", n//x)
        print(n, "is a prime number")

File loop

def main():
    file_name = input("What's the file path?")
        infile = open(file_name, 'r')
    except FileNotFoundError:
        print("\nFile not found")
        msum = 0.0
        count = 0
        line = infile.readline()
        while line != "":
            msum += eval(line)
            count += 1
            line = infile.readline()
        print("\nThe average of the numbers is", msum / count)



TKinter-Python standard GUI

1. Common Tk controls in 15 2. 3 layout management methods 3. Common attributes of controls Graphics-based on Tkinter extension

Insert picture description here


Insert picture description here


Insert picture description here


1. Common methods of GraphWin objects 2. General methods of graphic objects 3. Point object methods 4. Line object methods 5. Circle object methods 6, Rectangle object methods 7, Oval object methods 8, Polygon object methods 9, Text object methods Turtle—— Python built-in graphics library

Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Use graphics library to achieve interactive polygon drawing

from graphics import *

def main():
    win = GraphWin("Draw a polygon", 300, 300)
    win.setCoords(0, 0, 300, 300)
    message = Text(Point(150, 20), "CLick on five points")

    p1 = win.getMouse()
    p2 = win.getMouse()
    p3 = win.getMouse()
    p4 = win.getMouse()
    p5 = win.getMouse()

    polygon = Polygon(p1, p2, p3, p4, p5)

    message.setText("Click anywhere to quit.")


Use TKinter to implement a simple chat interface

from tkinter import *import time

def main():
    def send_msg():
        strMsg = "我:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\n"
        txtMsgList.insert(END, strMsg, 'greencolor')
        txtMsgList.insert(END, txtMsg.get('0.0', END))
        txtMsg.delete('0.0', END)

    def cancelMsg():
        txtMsg.delete('0.0', END)

    def send_msg_event(event):
        if event.keysym == "Up":

    # 创建窗口
    t = Tk()

    # 创建Frame容器
    frmLT = Frame(width=500, height=320, bg="white")
    frmLC = Frame(width=500, height=150, bg="white")
    frmLB = Frame(width=500, height=30)
    frmRT = Frame(width=200, height=500)

    # 创建控件
    txtMsgList = Text(frmLT)
    txtMsgList.tag_configure("greencolor", foreground="#008c00")  # 创建tag

    txtMsg = Text(frmLC)
    txtMsg.bind("<KeyPress-Up>", send_msg_event)

    btnSend = Button(frmLB, text='发送', width=8, command=send_msg)
    btnCancel = Button(frmLB, text='取消', width=8, command=cancelMsg)

    imgInfo = PhotoImage(file="python.gif")
    lblImage = Label(frmRT, image=imgInfo)
    lblImage.image = imgInfo

    # 窗口布局
    frmLT.grid(row=0, column=0, columnspan=2, padx=1, pady=3)
    frmLC.grid(row=1, column=0, columnspan=2, padx=1, pady=3)
    frmLB.grid(row=2, column=0, columnspan=2)
    frmRT.grid(row=0, column=2, rowspan=3, padx=2, pady=3)

    # 固定大小

    btnSend.grid(row=2, column=0)
    btnCancel.grid(row=2, column=1)



Use Turtle library to draw analog clock

from turtle import *from datetime import *

def Skip(step):

def mkHand(name, length):
    # 注册Turtle形状,建立表针Turtle
    Skip(-length * 0.1)
    forward(length * 1.1)
    handForm = get_poly()
    register_shape(name, handForm)

def Init():
    global secHand, minHand, hurHand, printer
    mode("logo")  # 重置Turtle指向北
    # 建立三个表针Turtle并初始化
    mkHand("secHand", 125)
    mkHand("minHand", 130)
    mkHand("hurHand", 90)
    secHand = Turtle()
    minHand = Turtle()
    hurHand = Turtle()
    for hand in secHand, minHand, hurHand:
        hand.shapesize(1, 1, 3)
    # 建立输出文字Turtle
    printer = Turtle()

def SetupClock(radius):
    # 建立表的外框
    for i in range(60):
        if i % 5 == 0:
            Skip(-radius - 20)

def Week(t):
    week = ["星期一", "星期二", "星期三",
            "星期四", "星期五", "星期六", "星期日"]
    return week[t.weekday()]

def Date(t):
    y = t.year
    m = t.month
    d =
    return "%s %d %d" % (y, m, d)

def Tick():
    # 绘制表针的动态显示
    t =
    second = t.second + t.microsecond * 0.000001
    minute = t.minute + second / 60.0
    hour = t.hour + minute / 60.0
    secHand.setheading(6 * second)
    minHand.setheading(6 * minute)
    hurHand.setheading(30 * hour)

    printer.write(Week(t), align="center",
                  font=("Courier", 14, "bold"))
    printer.write(Date(t), align="center",
                  font=("Courier", 14, "bold"))

    ontimer(Tick, 100)  # 100ms后继续调用tick

def main():

if __name__ == "__main__":

Use turtle library to draw snowflake map

import turtle as ttimport random as rd

def ground():
    for i in range(400):
        tt.pensize(rd.randint(5, 10))
        x = rd.randint(-400, 350)
        y = rd.randint(-280, -1)
        r = -y / 280
        g = -y / 280
        b = -y / 280
        tt.pencolor((r, g, b))
        tt.goto(x, y)
        tt.forward(rd.randint(40, 100))

def snow():
    for i in range(100):
        r = rd.random()
        g = rd.random()
        b = rd.random()
        tt.pencolor(r, g, b)
        tt.setx(rd.randint(-350, 350))
        tt.sety(rd.randint(1, 270))
        dens = rd.randint(8, 12)
        snowsize = rd.randint(10, 14)
        for j in range(dens):
            tt.right(360 / dens)

def main():
    tt.setup(800, 600, 0, 0)

if __name__ == "__main__":

Python library

1. Python library index provided by Python official website (opens new window)

2. Installation of Python library
Custom installation, go to the domestic mirror station to download the software Domestic pipy mirror station

Insert picture description here

Use the pip tool

File installation, through the .whl file installation

pip inatall xxx.whl

pip tool installation

pip source download address (opens new window)

Execute after decompression: python install

OS library commonly used functions

1. Commonly used functions of the OS library 2. os.path is a font library for handling operating systems. Commonly used functions of os.path 3. os.walk(path) is used to traverse a directory and return a triplet

Insert picture description here


Insert picture description here


root,dirs,files = os.walk(path)。

Root is a string, dirs and files are list types, representing all directories and all files in root.

sched library

1. The sched library is used for task scheduling.

2.sched.scheduler() is used to create a scheduled task.

3. When you need to schedule a task in time, use this function scheduler.enter(delay, priority, action, argument=()).

4. Delay indicates how much time to delay to execute.

5.priority indicates priority.

6. Action is a function that needs to be specifically scheduled.

7. Argument represents the parameter variable required by the action function.

8. runs all scheduled events in the scheduled task.

9. scheduler.cancel(event) cancels a scheduled event.

Function timing execution

import schedimport time

def print_time(msg='default'):
    print("当前时间", time.time(), msg)

s = sched.scheduler(time.time, time.sleep)print(time.time())
s.enter(5, 1, print_time, argument=("延迟5秒,优先级1",))
s.enter(3, 2, print_time, argument=("延迟3秒,优先级2",))
s.enter(3, 1, print_time, argument=("延迟3秒,优先级1",))
import os

path = input("请输入一个路径:")
for root, dirs, files in os.walk(path):
    for name in files:
        print(os.path.join(root, name))

Package and publish python applications (using the py2exe library)

1. Make sure that the python program can be executed, such as

2. Write a release script (same directory as, and name the python program that needs to be called and run in it.

from distutils.core import
 setupimport py2exe


3. Execute python py2exe under the command line.

4. After the program is executed correctly, a dist directory and a __pycache__ directory will be generated. The former contains the released exe program, and the latter can be deleted.

NumPy library

1. The NumPy system is an open source numerical calculation extension of Python that can store and process large matrices

N-dimensional array object Array.

Function library.

Practical linear algebra, Fourier transform and random number generation functions.

2. NumPy provides many advanced numerical programming tools

Matrix data type

Vector processing

Computing library

3. The main object of NumPy is a multidimensional array of the same kind of elements

Dimension is called axis

The number of axes is called rank

NumPy's array class is called ndarray, usually called array

Insert picture description here

1, create array

Use the array function to create an array using regular Python lists and primitive ancestors. The type of the created array is determined by the element type in the original sequence, for example: a=array([[1,2],[3,4]],dtype= complex).

Use placeholders to create an array. For example, the function zeros creates an array of all 0s, the function ones creates an array of all iss, and the function empty creates an array with random content and depends on the memory state.

Use arrange to create an array: arrange(10,30,5), starting from 10, adding 5 each time until 30 (not included)

2. Print an array, similar to a nested list.

3. The arithmetic operation of the array is carried out by element, and the multiplication operator * in NumPy indicates calculation by element.
4. Matrix multiplication can be realized by using dot function or creating matrix objects.

5. NumPy provides common mathematical functions such as sin, cos and exp.

6. NumPy does not use matrix operations by default for multi-dimensional array operations. For matrix operations on arrays, the corresponding functions can be called.

7. The NumPy library provides the matrix class. Matrix objects are created using the matrix class. Their addition, subtraction, multiplication, and division operations are calculated in a matrix manner.

8. Create a geometric series: numpy.logspace(1,10,3) means to generate 3 geometric series from 1 to 10.

9. Create a structure array:

  • Declare the structure array type: person=np.dtype({'names':['name','age'],'formats':['S32','i']})
  • Create a structure array: a = np.array([('zhang',12)],dtype=person)
  • Access the members of the structure array: a[0]['name']

10. More advanced operations: NumPy linear algebra sub-library linalg.

inv function: Calculate the inverse matrix.

solve function: Solve multiple linear equations.

Matplotlib library

1. Matplotlib is a data visualization library.

2. The pyplot sub-library provides basic functions for making 2D charts.

3. The histogram drawing function provided by matplotlib is hist().

4. The image sub-library of matplotlib can be used to manipulate images.

  • The imread() function stores the RGB value of each pixel of the image into an array.
  • The imshow() function displays the image array with RGB values ​​as an image.

Use Matplotlib library to draw curves

import matplotlib.pyplot as pltimport numpy as np

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)
z = np.cos(x * x)

plt.figure(figsize=(8, 4))
plt.plot(x, z, "ro", label="$cos(x^2)$")
plt.plot(x, y, label="$sin(x)$")


Use the function of Matplotlib sub-figure

import numpy as npimport matplotlib.pyplot as plt

w = np.linspace(0.1, 1000, 1000)
p = np.abs(1 / (1 + 0.1j * w))

plt.plot(w, p, linewidth=2)
plt.ylim(0, 1.5)

plt.semilogx(w, p, linewidth=2)
plt.ylim(0, 1.5)

plt.semilogy(w, p, linewidth=2)
plt.ylim(0, 1.5)

plt.loglog(w, p, linewidth=2)
plt.ylim(0, 1.5)


1. wxPython is a package of wxWidgets in python language, wxWidgets is a cross-platform GUI application program interface, written in C++.

2. For Python3, the download address of wxPython (opens new window), pay attention to selecting the corresponding python version number and the number of digits of the computer.
3. Control events:

  • Button click
  • Changes to the content of the text field
  • Mouse over
  • Double click
  • Keyboard press

Absolute layout using wxPython

# -*-coding:utf8-*-import wx

class Lesson(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=-1, title=u'极客学院', size=(600, 600))
        panel = wx.Panel(self, -1)

        button = wx.Button(panel, label=u'我是按钮', pos=(20, 0), size=(100, 100))
        statictext = wx.StaticText(panel, -1, u'我是不能编辑的文本框', pos=(20, 100))
        text = wx.TextCtrl(panel, -1, u'请在这里输入内容', pos=(200, 210))
        password = wx.TextCtrl(panel, -1, u'请在这里输入内容', style=wx.TE_PASSWORD, pos=(200, 250))
        mutiText = wx.TextCtrl(panel, -1, u'我是多行\n文本框', style=wx.TE_MULTILINE, pos=(100, 300))
        checkBox1 = wx.CheckBox(panel, -1, u"我是复选框1", pos=(150, 20))
        checkBox2 = wx.CheckBox(panel, -1, u"我是复选框2", pos=(150, 40))

        radio1 = wx.RadioButton(panel, -1, u"我是单选按钮1", pos=(150, 60), style=wx.RB_GROUP)
        radio2 = wx.RadioButton(panel, -1, u"我是单选按钮2", pos=(150, 80))
        radio3 = wx.RadioButton(panel, -1, u"我是单选按钮3", pos=(150, 100))

        radioList = [u'一组单选按钮之1', u'一组单选按钮之2', u'一组单选按钮之3']
        wx.RadioBox(panel, -1, u"一组单选按钮", (10, 120), wx.DefaultSize, radioList, 2, wx.RA_SPECIFY_ROWS)

        jikexueyuan = [u'极', u'客', u'学', u'院', '1', '2', '3', '4', '5', '6']
        listBox = wx.ListBox(panel, -1, pos=(300, 20), size=(100, 100), choices=jikexueyuan, style=wx.LB_MULTIPLE)

        img = wx.Image(r'python.gif', wx.BITMAP_TYPE_ANY).Scale(100, 200)
        sb1 = wx.StaticBitmap(panel, -1, wx.BitmapFromImage(img), pos=(300, 300))

if __name__ == "__main__":
    app = wx.App()
    frame = Lesson()

Relative layout using wxPython

# -*-coding:utf8-*-
import wx

class Lesson(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=-1, title=u'极客学院', size=(600, 600))
        self.panel = wx.Panel(self, -1)

        # 定义我们需要的各个控件

        commandStatic = wx.StaticText(self.panel, -1, u'输命令:')
        writePyStatic = wx.StaticText(self.panel, -1, u'写代码:')

        commandText = wx.TextCtrl(self.panel, -1, u'')
        writePyText = wx.TextCtrl(self.panel, -1, u'''#-*-coding:utf-8-*-\n#在这写Python代码''',
                                  style=wx.TE_MULTILINE, size=(300, 200))

        send = wx.Button(self.panel, label=u'发送命令')
        clear = wx.Button(self.panel, label=u'清空命令')
        screen = wx.Button(self.panel, label=u'查看屏幕')

        serverList = ['', '', '', '', '', '']
        server = wx.ListBox(self.panel, -1, size=(120, 100), choices=serverList, style=wx.LB_SINGLE)

        img = wx.Image(r'python_logo.gif', wx.BITMAP_TYPE_ANY).Scale(200, 200)
        screenBox = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(img))

        # 基于BoxSizer布局
        # hBoxAll = wx.BoxSizer(wx.HORIZONTAL)
        # vBoxControl = wx.BoxSizer(wx.VERTICAL)
        # hBoxCommand = wx.BoxSizer(wx.HORIZONTAL)
        # vBoxWrite = wx.BoxSizer(wx.VERTICAL)
        # hBoxButton = wx.BoxSizer(wx.HORIZONTAL)
        # hBoxCommand.Add(commandStatic, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        # hBoxCommand.Add(commandText, proportion=2, flag=wx.ALL | wx.EXPAND, border=5)
        # vBoxWrite.Add(writePyStatic, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
        # vBoxWrite.Add(writePyText, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
        # vBoxControl.Add(hBoxCommand, proportion=0, flag=wx.ALL, border=5)
        # vBoxControl.Add(vBoxWrite, proportion=0, flag=wx.ALL, border=5)
        # hBoxButton.Add(send, proportion=0, flag=wx.ALL, border=5)
        # hBoxButton.Add(clear, proportion=0, flag=wx.ALL, border=5)
        # hBoxButton.Add(screen, proportion=0, flag=wx.ALL, border=5)
        # vBoxControl.Add(hBoxButton, proportion=0, flag=wx.ALL, border=5)
        # hBoxAll.Add(server, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        # hBoxAll.Add(vBoxControl, proportion=2, flag=wx.ALL | wx.EXPAND, border=5)
        # hBoxAll.Add(screenBox, proportion=3, flag=wx.ALL | wx.EXPAND, border=5)
        # self.panel.SetSizer(hBoxAll)
        # hBoxAll.Fit(self)

        # 基于GridSizer布局
        # gridSizerAll= wx.GridSizer(rows=3, cols=3, hgap=5, vgap=5)
        # gridSizerAll.AddMany([(server, 0, wx.EXPAND), (commandStatic, 0, wx.EXPAND), (commandText, 0, wx.EXPAND),
        # (writePyStatic, 0, wx.EXPAND), (send, 0, wx.EXPAND), (clear, 0, wx.EXPAND),
        #                      (writePyText, 0, wx.EXPAND), (screen, 0, wx.EXPAND), (screenBox, 0, wx.EXPAND)])
        # self.panel.SetSizer(gridSizerAll)
        # gridSizerAll.Fit(self)

        # flexGridSizerAll = wx.FlexGridSizer(rows=3, cols=3, hgap=5, vgap=5)
        # flexGridSizerAll.AddMany([(server, 0, wx.EXPAND), (commandStatic, 0, wx.EXPAND), (commandText, 0, wx.EXPAND),
        #                           (writePyStatic, 0, wx.EXPAND), (send, 0, wx.EXPAND), (clear, 0, wx.EXPAND),
        #                           (writePyText, 0, wx.EXPAND), (screen, 0, wx.EXPAND), (screenBox, 0, wx.EXPAND)])
        # self.panel.SetSizer(flexGridSizerAll)
        # flexGridSizerAll.AddGrowableCol(2, 1)
        # flexGridSizerAll.AddGrowableRow(2, 1)
        # flexGridSizerAll.Fit(self)

        gridBagSizerAll = wx.GridBagSizer(hgap=5, vgap=5)
        gridBagSizerAll.Add(server, pos=(0, 0),
                            flag=wx.ALL | wx.EXPAND,
                            span=(7, 2), border=5)

        gridBagSizerAll.Add(commandStatic, pos=(0, 2),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
        gridBagSizerAll.Add(commandText, pos=(0, 3),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(1, 2), border=5)

        gridBagSizerAll.Add(writePyStatic, pos=(1, 2),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(1, 3), border=5)
        gridBagSizerAll.Add(writePyText, pos=(2, 2),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(4, 3), border=5)
        gridBagSizerAll.Add(send, pos=(6, 2),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(1, 1), border=5)
        gridBagSizerAll.Add(clear, pos=(6, 3),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(1, 1), border=5)
        gridBagSizerAll.Add(screen, pos=(6, 4),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(1, 1), border=5)

        gridBagSizerAll.Add(screenBox, pos=(0, 5),
                            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                            span=(7, 2), border=5)


        self.SetSizeHints(250, 200, 700, 400)  # 设定窗口的最大最小值
        # gridBagSizerAll.AddGrowableCol(0, 1)
        # gridBagSizerAll.AddGrowableCol(1, 1)
        # gridBagSizerAll.AddGrowableCol(2, 1)
        # gridBagSizerAll.AddGrowableCol(3, 1)
        # gridBagSizerAll.AddGrowableCol(4, 1)
        # gridBagSizerAll.AddGrowableCol(5, 1)
        # gridBagSizerAll.AddGrowableCol(6, 1)
        # gridBagSizerAll.AddGrowableRow(0, 1)
        # gridBagSizerAll.AddGrowableRow(1, 1)
        # gridBagSizerAll.AddGrowableRow(2, 1)
        # gridBagSizerAll.AddGrowableRow(3, 1)
        # gridBagSizerAll.AddGrowableRow(4, 1)
        # gridBagSizerAll.AddGrowableRow(5, 1)
        # gridBagSizerAll.AddGrowableRow(6, 1)

if __name__ == "__main__":
    app = wx.App()
    frame = Lesson()

wxPython event programming

# -*-coding:utf8-*-
import time
import wx

class Example3(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=-1, title=u'极客学院', size=(600, 600))
        self.panel = wx.Panel(self, -1)

        # 定义我们需要的各个控件

        commandStatic = wx.StaticText(self.panel, -1, u'输命令:')
        writePyStatic = wx.StaticText(self.panel, -1, u'写代码:')

        self.commandText = wx.TextCtrl(self.panel, -1, u'')
        self.writePyText = wx.TextCtrl(self.panel, -1, u'''#-*-coding:utf-8-*-\n#在这写Python代码''',
                                       style=wx.TE_MULTILINE, size=(300, 200))

        self.send = wx.Button(self.panel, label=u'发送命令')
        self.clear = wx.Button(self.panel, label=u'清空命令')
        self.screen = wx.Button(self.panel, label=u'查看屏幕')

        self.serverList = ['', '', '', '', '', '']
        self.server = wx.ListBox(self.panel, -1, size=(120, 100), choices=self.serverList, style=wx.LB_SINGLE)

        img = wx.Image(r'python_logo.gif', wx.BITMAP_TYPE_ANY).Scale(200, 200)
        self.screenBox = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(img))

        self.Bind(wx.EVT_BUTTON, self.onSend, self.send)
        self.Bind(wx.EVT_BUTTON, self.onClear, self.clear)
        self.Bind(wx.EVT_BUTTON, self.onScreen, self.screen)

        # 基于GirdBagSizer布局
        self.gridBagSizerAll = wx.GridBagSizer(hgap=5, vgap=5)
        self.gridBagSizerAll.Add(self.server, pos=(0, 0),
                                 flag=wx.ALL | wx.EXPAND,
                                 span=(7, 2), border=5)

        self.gridBagSizerAll.Add(commandStatic, pos=(0, 2),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
        self.gridBagSizerAll.Add(self.commandText, pos=(0, 3),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(1, 2), border=5)

        self.gridBagSizerAll.Add(writePyStatic, pos=(1, 2),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(1, 3), border=5)
        self.gridBagSizerAll.Add(self.writePyText, pos=(2, 2),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(4, 3), border=5)
        self.gridBagSizerAll.Add(self.send, pos=(6, 2),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(1, 1), border=5)
        self.gridBagSizerAll.Add(self.clear, pos=(6, 3),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(1, 1), border=5)
        self.gridBagSizerAll.Add(self.screen, pos=(6, 4),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(1, 1), border=5)

        self.gridBagSizerAll.Add(self.screenBox, pos=(0, 5),
                                 flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                                 span=(7, 2), border=5)


        # self.SetSizeHints(250, 200, 700, 400) #设定窗口的最大最小值
        self.gridBagSizerAll.AddGrowableCol(0, 1)
        self.gridBagSizerAll.AddGrowableCol(1, 1)
        self.gridBagSizerAll.AddGrowableCol(2, 1)
        self.gridBagSizerAll.AddGrowableCol(3, 1)
        self.gridBagSizerAll.AddGrowableCol(4, 1)
        self.gridBagSizerAll.AddGrowableCol(5, 1)
        self.gridBagSizerAll.AddGrowableCol(6, 1)

        self.gridBagSizerAll.AddGrowableRow(0, 1)
        self.gridBagSizerAll.AddGrowableRow(1, 1)
        self.gridBagSizerAll.AddGrowableRow(2, 1)
        self.gridBagSizerAll.AddGrowableRow(3, 1)
        self.gridBagSizerAll.AddGrowableRow(4, 1)
        self.gridBagSizerAll.AddGrowableRow(5, 1)
        self.gridBagSizerAll.AddGrowableRow(6, 1)

    def onSend(self, event):
        if self.server.GetSelection() != -1:
            server = self.serverList[self.server.GetSelection()]
            server = u'未选择服务器'
        command = self.commandText.GetValue()
        writePy = self.writePyText.GetValue()
        print(u'选中的服务器是: %s' % server)
        print(u'执行的内置命令是: %s' % command)
        print(u'写入的Python代码是:\n%s' % writePy)

    def onClear(self, event):

    def onScreen(self, event):
        img = wx.Image(r'python.gif', wx.BITMAP_TYPE_ANY).Scale(300, 200)

if __name__ == "__main__":
    app = wx.App()
    frame = Example3()

Multithreaded programming in Python

1. thread.start_new_thread(function name, (parameter 1, parameter 2, ···)).

2. Or use the Threading module to create threads.

Everyone has read articles for so long, you can order a collection. Break! ! ! Then look again. Don't forget! You need to persevere in your studies to make progress. come on! Come on! ! !

Insert picture description here

scipy library

1. Solve the system of nonlinear equations

scipy.optimize子库中的fsolve函数:fsolve(函数, 初始解, 雅可比矩阵)
from math import sin, cos
from scipy.optimize import fsolve

def func(x):
    x0, x1, x2 = x.tolist()
    return [
        5 * x1 + 3,
        4 * x0 * x0 - 2 * sin(x1 * x2),
        x1 * x2 - 1.5

def j(x):
    x0, x1, x2 = x.tolist()
    return [
        [0, 5, 0],
        [8 * x0, -2 * x2 * cos(x1 * x2), -2 * x1 * cos(x1 * x2)],
        [0, x2, x1]

r = fsolve(func, [1, 1, 1], fprime=j)

Friends who have come back from rest are awesome, friends who have not rested are even better. Let's continue to look down! ! !

Insert picture description here

2. Numerical integration

  • The quad function in the scipy.integrate sub-library:
    One-fold integral: quad (function, lower bound of definite integral, upper bound of definite integral)
    Double integral: dblquad
    Triple integral: tplquad
from scipy.integrate import quad

def func(x):
    return (1 - x * x) ** 0.5

p, err = quad(func, -1, 1)print(2 * p)

Solve ordinary differential equations

1. odeint in the scipy.integrate sub-library

from scipy.integrate import odeintimport numpy as npfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt

def lorenz(w, t, p, r, b):
    x, y, z = w
    return np.array([p * (y - x), x * (r - z), x * y - b * z])

t = np.arange(0, 30, 0.01)
track = odeint(lorenz, (0.0, 1.00, 0.0), t, args=(10.0, 28.0, 3.0))

fig = plt.figure()
ax = Axes3D(fig)
ax.plot(track[:, 0], track[:,1], track[:,2])

Numerical differentiation

1. Derivative in the scipu.misc sub-library

import numpy as np
import matplotlib.pyplot as pltfrom scipy.misc 
import derivative

Ex = lambda q: q ** 2
x0 = np.linspace(-10, 10, 1000)
dEx = derivative(Ex, x0, dx=1e-6)
plt.plot(x0, dEx)

mpl_toolkits library

from mpl_toolkits.mplot3d 
import Axes3Dimport numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = Axes3D(fig)
th = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(th)
y = r * np.cos(th)


Insert picture description here

Pay attention to the Suzhou program, continue to update technology sharing. Thank you all for your support

Insert picture description here