Python 3 entry, see this is enough

Light ink green shirt 2021-02-20 23:09:58
python entry

Python 3 introduction , Just read this one

Python And the binary code of the magnifying glass

brief introduction

Python It's a high-level combination of explanatory 、 Compilability 、 Interactive and object-oriented scripting language .Python from Guido van Rossum On 1989 It was invented at the National Institute of mathematics and computer science in the Netherlands at the end of the year , The first public release was released in 1991 year .


  • Easy to learn :Python There are relatively few keywords , Simple structure , And a clearly defined grammar , It's easier to learn .
  • Easy to read :Python More clearly defined code .
  • Easy to maintain :Python The success is that its source code is fairly easy to maintain .
  • An extensive library of standards :Python One of the biggest advantages of is rich libraries , Cross platform , stay UNIX,Windows and macOS Very compatible .
  • Interactive mode : The support of interactive mode , You can enter the execution code from the terminal and get result Language , Interactive test and debug code snippets .
  • portable : Based on its open source features ,Python It's been transplanted ( That is to make it work ) To many platforms .
  • Scalable : If you need a piece of critical code that runs fast , Or I want to write some algorithms that don't want to be open , You can use C or C++ Complete that part of the program , And then from your Python Call in program .
  • database :Python Interface to all major business databases .
  • GUI Programming :Python Support GUI Can be created and ported to many system calls .
  • Embeddable : You can take Python Embedded in C/C++ Program , Let users of your program get ” scripting ” The ability of .
  • object-oriented :Python Is a strong object-oriented language , Anything in a program is called an object , Including digital 、 character string 、 Functions, etc .

Basic grammar

function Python

Interactive interpreter

Execute... In the command line window python after , Get into Python The interactive interpreter .exit() or Ctrl + D Key combination exit interactive interpreter .

Command line scripts

Execute... In the command line window python, To carry out Python Script files .

Specify interpreter

If in Python First line input of script file #!/usr/bin/env python, Then it can be executed in the command line window /path/to/ To execute the script file .

notes : This method does not support Windows Environmental Science .


By default ,3.x Source files are UTF-8 code , All strings are Unicode character . You can also specify the file encoding manually :

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


# encoding: utf-8

Be careful : The line label must be on the first line of the file


  • The first character must be an English letter or an underline _ .
  • The rest of the identifier consists of the letters 、 Numbers and underscores .
  • Identifiers are case sensitive .

notes : from 3.x Start , Not ASCII Identifiers are also allowed , But not recommended .

Reserved words

Reserved words are keywords , We can't use them as any identifier names .Python The standard library of provides a keyword modular , You can output all keywords of the current version :

>>> import keyword>>> keyword.kwlist['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


Single line notes using #, Multiline comments use ''' or """.

# This is a single line comment ''' This is a multiline comment. This is a multiline comment '''""" This is also a multiline comment, which is also a multiline comment """

Lines and indents

Python The most distinctive feature is the use of indentation to represent code blocks , You don't need braces {}. The number of indented spaces is variable , But the statements of the same code block must contain the same number of indented spaces . Indents are inconsistent , Can cause a run error .

Multi line statement

Python It's usually a sentence written one line at a time , But if the sentence is long , We can use backslashes to implement multiline statements .

total = item_one + item_two + item_three

stay [], {}, or () Multiple lines in , No need to use backslash .

Blank line

Functions or methods of classes are separated by empty lines , Represents the beginning of a new piece of code . Classes and function entries are also separated by a blank line , To highlight the beginning of the function entry .

Blank lines are not the same as code indentation , Air travel is not Python Part of grammar . Don't insert blank lines when writing ,Python The interpreter will not run wrong . But blank lines are used to separate two pieces of code with different functions or meanings , Easy to maintain or refactor the code in the future .

remember : Blank lines are also part of the program code .

Waiting for user input

input Function to wait and receive user input from the command line .

content = input(" Please enter something and press Enter key ")print(content)

Write multiple statements on the same line

Python You can use multiple statements on the same line , Use semicolons... Between statements ; Division .

import sys; x = 'hello world'; sys.stdout.write(x + '')

Multiple statements make up a code group

Indent the same set of statements into a block of code , We call it code group .

image if、while、def and class Such compound statements , The first line starts with keywords , With a colon : end , One or more lines of code following this line form a code group .

We call the first and subsequent code groups a clause (clause).

print Output

print The default output is line feed , If you want to implement no line wrapping, you need to add... At the end of the variable end="" Or other non newline character string :

print('123') # Default newline print('123', end = "") # Don't wrap 

import And from…import

stay Python use import perhaps from...import To import the corresponding module .

Import the whole module into , The format is :import module_name

Import a function from a module , The format is :from module_name import func1

Import multiple functions from a module , The format is :from module_name import func1, func2, func3

Import all functions in a module into , The format is :from module_name import *


Arithmetic operator

Operator description + Add - reduce * ride / except % modulus ** power // Divide and conquer

Comparison operator

Operator description == be equal to != It's not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to

Assignment operator

Operator description = Simple assignment operators += Addition assignment operator -= Subtraction assignment operator *= Multiplication assignment operator /= Division assignment operator %= Modulo assignment operator **= Power assignment operator //= Integer division assignment operator

An operator

Python 3 introduction , Just read this one

Logical operators

Python 3 introduction , Just read this one

member operator

Python 3 introduction , Just read this one

Identity operator

Python 3 introduction , Just read this one

Operator priority

Python 3 introduction , Just read this one

Operators with the same priority will proceed from left to right . Use parentheses () You can change the order of operations .


Variables must be changed before they are used ” Definition ”( That is to give a value to the variable ), Otherwise, an error will be reported :

>>> nameTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'name' is not defined

data type

Boolean (bool)

Only True and False Two values , It means true or false .

Numbers (number)

integer (int)

An integer value , It can be positive or plural , No decimal . 3.x There is no limit to the size of an integer , Can be viewed as Long Type used , therefore 3.x No, 2.x Of Long type .

floating-point (float)

Floating point type consists of integer part and decimal part , Floating point types can also be represented by scientific notation (2.5e2 = 2.5 x 10^2 = 250)

The plural (complex)

The plural consists of the real part and the imaginary part , It can be used a + bj, perhaps complex(a,b) Express , The real part of a complex number a Deficiency part of harmony b It's all floating point .

Number operation

  • Different types of number mixing operations convert integers to floating-point numbers
  • The result of floating-point operation may be different on different machines
  • In integer division , division / Always return a floating point number , If you just want to get the result of integers , Discard possible fractions , You can use operators //.
  • // What you get is not necessarily a number of integer type , It has something to do with the data type of denominator
  • In interactive mode , Finally, the output expression result is assigned to the variable _,_ It's a read-only variable

Mathematical functions

notes : Use of the following functions , Import first math package .

Python 3 introduction , Just read this one

Random number function

notes : Use of the following functions , Import first random package .

Python 3 introduction , Just read this one

Trigonometric functions

notes : Use of the following functions , Import first math package .

Python 3 introduction , Just read this one

Mathematical constant

Python 3 introduction , Just read this one

character string (string)

  • Single quotation marks and double quotation marks use exactly the same
  • Use three quotes (''' or """) You can specify a multiline string
  • Escape character ( The backslash ) It can be used to escape , Use r You can keep the backslash from escaping , Such as r"this is a line with ", Is displayed , It's not a new line
  • Concatenate strings literally , Such as "this " "is " "string" Will be automatically converted to this is string
  • String can be used + Operators join together , use * Operator repetition
  • There are two ways to index strings , From left to right 0 Start , From right to left -1 Start
  • String cannot be changed
  • No separate character type , One character is the length of 1 String
  • The syntax format of string truncation is as follows : Variable [ Header subscript : Tail subscript ]

Escape character

Python 3 introduction , Just read this one

String operators

Python 3 introduction , Just read this one

String formatting

stay Python in , String formatting is not sprintf function , It's about using % Symbol . for example :

print(" My name is %s, This year, %d year !" % (' Xiao Ming ', 10))// Output : My name is Xiao Ming , This year, 10 year !

Format symbol :

Python 3 introduction , Just read this one

Auxiliary instructions :

Python 3 introduction , Just read this one

Python 2.6 Start , Added a function to format strings str.format(), It enhances string formatting .

Multiline string

  • Use three Quotes (''' or """) Package string content
  • Escape characters are supported for multiline string content , The usage is the same as single and double quotation marks
  • The contents of the package , There are variables to receive or operate on, that is, strings , Otherwise, it's a multiline comment

example :

string = '''print(math.fabs(-10))print(random.choice(li))'''print(string)

Output :

print( math.fabs(-10))print(random.choice(li))


stay 2.x in , A normal string is a 8 position ASCII Code for storage , and Unicode The string is stored as 16 position Unicode character string , This can represent more character sets . The syntax used is to prefix a string u.

stay 3.x in , All strings are Unicode character string .

String function

Python 3 introduction , Just read this one

Python 3 introduction , Just read this one

Python 3 introduction , Just read this one

byte (bytes)

stay 3.x in , String and binary data are completely separate . The text is always Unicode, from str Type said , Binary data is provided by bytes Type said .Python 3 They are not used in arbitrary implicit ways str and bytes, You can't splice strings and byte streams , You can't search a string in a byte stream ( vice versa ), You can't pass in a string as a function of a byte stream ( vice versa ).

  • bytes The type and str type , There are only two ways encode() and decode() Different .
  • bytes Type data should be in the normal str Add before type b To differentiate , for example b'abc'.
  • Only when it is necessary to str code (encode) become bytes When , such as : Transmitting data over the network ; Or you need to bytes decode (decode) become str When , We'll focus on it str and bytes The difference between .

bytes turn str:

b'abc'.decode()str(b'abc')str(b'abc', encoding='utf-8')

str turn bytes:

' China '.encode()bytes(' China ', encoding='utf-8')

list (list)

  • A list is an unordered list 、 Repeatable data sequence , You can add... At any time 、 Delete the elements in it .
  • Each element of the list page is assigned a numeric index , from 0 Start
  • Lists are created using square brackets , Use commas to separate elements
  • List element values can be of any type , Including variable
  • Use square brackets for element access to the list 、 section 、 modify 、 Delete and other operations , The open close interval is [) form
  • The element access of the list can be nested
  • Any expression can be in square brackets

Create a list of

hello = (1, 2, 3)li = [1, "2", [3, 'a'], (1, 3), hello]

Access elements

li = [1, "2", [3, 'a'], (1, 3)]print(li[3]) # (1, 3)print(li[-2]) # [3, 'a']

Slice access

Format : list_name[begin:end:step] begin Indicates the starting position ( The default is 0),end Indicates the end position ( Default to last element ),step Indicating step size ( The default is 1)

hello = (1, 2, 3)li = [1, "2", [3, 'a'], (1, 3), hello]print(li) # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)]print(li[1:2]) # ['2']print(li[:2]) # [1, '2']print(li[:]) # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)]print(li[2:]) # [[3, 'a'], (1, 3), (1, 2, 3)]print(li[1:-1:2]) # ['2', (1, 3)]

Access embedded list The elements of :

li = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ['a', 'b', 'c']]print(li[1:-1:2][1:3]) # (3, 5)print(li[-1][1:3]) # ['b', 'c']print(li[-1][1]) # b

Modify the list

By using square brackets , You can modify the elements of the list very flexibly 、 Replace 、 Delete and other operations .

li = [0, 1, 2, 3, 4, 5]li[len(li) - 2] = 22 # modify [0, 1, 2, 3, 22, 5]li[3] = 33 # modify [0, 1, 2, 33, 4, 5]li[1:-1] = [9, 9] # Replace [0, 9, 9, 5]li[1:-1] = [] # Delete [0, 5]

Remove elements

It can be used del Statement to delete a specified range of elements from the list .

li = [0, 1, 2, 3, 4, 5]del li[3] # [0, 1, 2, 4, 5]del li[2:-1] # [0, 1, 5]

List operators

  • + Used to merge lists
  • * Used for repeating list elements
  • in Used to determine whether an element exists in a list
  • for ... in ... Used to traverse list elements
[1, 2, 3] + [3, 4, 5] # [1, 2, 3, 3, 4, 5][1, 2, 3] * 2 # [1, 2, 3, 1, 2, 3]3 in [1, 2, 3] # Truefor x in [1, 2, 3]: print(x) # 1 2 3

List functions

  • len(list) Number of list elements
  • max(list) The maximum value in a list element
  • min(list) Minimum value in list element
  • list(seq) Converts a tuple to a list
li = [0, 1, 5]max(li) # 5len(li) # 3

notes : Use on list max/min function ,2.x Element value type is not required in ,3.x The element value type must be consistent .

Tabular method

  • list.append(obj)
  • Add a new object at the end of the list
  • list.count(obj)
  • Returns the number of times an element appears in a list
  • list.extend(seq)
  • Appends multiple values from another sequence at once at the end of the list
  • list.index(obj)
  • Returns the index location of the lookup object , Throw an exception if the object is not found
  • list.insert(index, obj)
  • Inserts the specified object into the specified location in the list
  • list.pop([index=-1]])
  • Removes an element from the list ( Default last element ), And returns the value of that element
  • list.remove(obj)
  • Removes the first match of a value in the list
  • list.reverse()
  • Reverse sort the elements of the list
  • list.sort(cmp=None, key=None, reverse=False)
  • Sort the original list , If you specify parameters , Then use the comparison function specified by the comparison function
  • list.clear()
  • clear list You can also use del list[:]、li = [] Etc
  • list.copy()
  • Copy list By default, an equal sign is used to assign a value to another variable , It's actually a reference to a list variable . If we want to achieve

List derivation

List derivation provides a simple way to create a list from a sequence . Usually an application applies some operations to each element of a sequence , Use the result as an element to generate a new list , Or create subsequences according to certain criteria .

Every list derivation is in for Followed by an expression , Then there are zero to many for or if Clause . The return result is based on the expression from the following for and if The list generated in the context . If you want the expression to derive a tuple , You have to use brackets .

Multiply each value in the list by three , Get a new list :

vec = [2, 4, 6][(x, x**2) for x in vec]# [(2, 4), (4, 16), (6, 36)]

Call a method one by one for each element in the sequence :

freshfruit = [' banana', ' loganberry ', 'passion fruit '][weapon.strip() for weapon in freshfruit]# ['banana', 'loganberry', 'passion fruit']

use if Clause as filter :

vec = [2, 4, 6][3*x for x in vec if x > 3]# [12, 18]vec1 = [2, 4, 6]vec2 = [4, 3, -9][x*y for x in vec1 for y in vec2]# [8, 6, -18, 16, 12, -36, 24, 18, -54][vec1[i]*vec2[i] for i in range(len(vec1))]# [8, 12, -54]

List nesting parsing :

matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9],]new_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]print(new_matrix)# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Tuples (tuple)

  • Tuples are similar to lists , The difference is that the elements of a tuple cannot be modified
  • Tuples use braces , Use square brackets for lists
  • Tuples are easy to create , You just need to add elements in parentheses , And separate them with commas
  • No, append(),insert() This is the way to make changes , Other methods are the same as lists
  • The key in the dictionary must be unique and immutable , There is no limit to the value
  • When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators

Access tuples

The way tuples are accessed is the same as lists . Tuple elements can be assigned directly to multiple variables , But the number of variables must be the same as the number of elements .

a, b, c = (1, 2, 3)print(a, b, c)

Combinatorial tuple

Element values in tuples are not allowed to be modified , But we can join tuples

tup1 = (12, 34.56);tup2 = ('abc', 'xyz')tup3 = tup1 + tup2;print (tup3)# (12, 34.56, 'abc', 'xyz')

Delete tuples

Element values in tuples are not allowed to be deleted , But we can use del Statement to delete the entire tuple

Tuple function

  • len(tuple) Number of tuple elements
  • max(tuple) The maximum value in a tuple element
  • min(tuple) The minimum value in a tuple element
  • tuple(tuple) Convert list to tuple

Tuple derivation

t = 1, 2, 3print(t)# (1, 2, 3)u = t, (3, 4, 5)print(u)# ((1, 2, 3), (3, 4, 5))

Dictionaries (dict)

  • Dictionary is another variable container model , Any type of object can be stored
  • Each key value of the dictionary (key=>value) Yes, with a colon (:) Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets ({}) in
  • The key must be unique , But values don't have to be
  • Values can be any data type
  • The key must be immutable , for example : Numbers 、 character string 、 Tuples can , But the list doesn't work
  • If you access data with keys that are not in the dictionary , Will report a mistake
  • The elements of the dictionary are out of order , Element cannot be referenced by subscript , Reference by key
  • The order and method of storing in dictionary key It doesn't matter in what order

The format is as follows :

d = {key1 : value1, key2 : value2 }

Visit the dictionary

dis = {'a': 1, 'b': [1, 2, 3]}print(dis['b'][2])

Revise the dictionary

dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}}dis[9]['name'] = 999print(dis)# {'a': 1, 9: {'name': 999}, 'b': [1, 2, 3]}

Delete Dictionary

use del Statement to delete a dictionary or an element of a dictionary .

dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}}del dis[9]['name']print(dis)del dis # Delete Dictionary # {'a': 1, 9: {}, 'b': [1, 2, 3]}

Dictionary function

  • len(dict) Count the number of dictionary elements , That's the total number of bonds
  • str(dict) Output Dictionary , In a printable string
  • type(variable) Returns the type of variable entered , If the variable is a dictionary, return the dictionary type
  • key in dict Determine whether the key exists in the dictionary

Dictionary method

  • dict.clear()
  • Delete all elements in the dictionary
  • dict.copy()
  • Returns a shallow copy of a dictionary
  • dict.fromkeys(seq[, value])
  • Create a new dictionary , In sequence seq The middle element is the key of the dictionary ,value Is the initial value of all keys in the dictionary
  • dict.get(key, default=None)
  • Returns the value of the specified key , If the value is not in the dictionary, return the default value
  • dict.items()
  • Return traversable... As a list ( key , value ) Tuple array
  • dict.keys()
  • Return all keys of a dictionary as a list
  • dict.values()
  • Returns all values in the dictionary as a list
  • dict.setdefault(key, default=None)
  • If key In the dictionary , Return the corresponding value . If it's not in the dictionary , The insert key And set the default value default, And back to default ,default The default value is None.
  • dict.update(dict2)
  • Put the dictionary parameter dict2 Key / Value pair update to dictionary dict in
dic1 = {'a': 'a'}dic2 = {9: 9, 'a': 'b'}dic1.update(dic2)print(dic1)# {'a': 'b', 9: 9}
  • dict.pop(key[,default])
  • Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given , Otherwise return to default value .
  • dict.popitem()
  • Randomly return and delete a pair of keys and values in the dictionary ( Generally delete the end pair )

Dictionary derivation

Constructors dict() Building a dictionary directly from a list of key value pairs tuples . If there is a fixed pattern , List derivation specifies a specific key value pair :

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){'sape': 4139, 'jack': 4098, 'guido': 4127}

Besides , The dictionary can be used to create a dictionary of arbitrary values and values :

>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}

If the keyword is just a simple string , It is sometimes more convenient to specify key value pairs with keyword parameters :

>>> dict(sape=4139, guido=4127, jack=4098){'sape': 4139, 'jack': 4098, 'guido': 4127}

aggregate (set)

A set is an unordered sequence of non repeating elements

Create set

  • You can use braces {} perhaps set() Function to create a collection
  • To create an empty collection, you must use the set() instead of {}, because {} Is used to create an empty dictionary
  • set(value) How to create a collection ,value Can be a string 、 list 、 Tuples 、 Dictionary and other sequence types
  • establish 、 add to 、 Modification and other operations , The assembly will automatically de weight
{1, 2, 1, 3} # {} {1, 2, 3}set('12345') # character string {'3', '5', '4', '2', '1'}set([1, 'a', 23.4]) # list {1, 'a', 23.4}set((1, 'a', 23.4)) # Tuples {1, 'a', 23.4}set({1:1, 'b': 9}) # Dictionaries {1, 'b'}

Additive elements

Put the element val Add to collection set in , If the element already exists , Nothing is done :


It can also be used. update Method to batch add elements , Parameters can be lists , Tuples , Dictionary, etc :

set.update(list1, list2,...)

Remove elements

If there are elements val The remove , If it doesn't exist, report it wrong :


If there are elements val The remove , It doesn't exist and doesn't report a mistake :


Remove an element at random :


Element number

Just like other sequences , It can be used len(set) Get the number of elements in the collection .

Empty the set

set.clear()set = set()

Determine whether an element exists

val in set

Other methods

  • set.copy()
  • Copy Collection
  • set.difference(set2)
  • Difference set , stay set But not in set2 in
  • set.intersection(set2)
  • Find the intersection , At the same time set and set2 in
  • set.union(set2)
  • Union , all set and set2 The elements of
  • set.symmetric_difference(set2)
  • Find the symmetric difference set , Elements that appear in two sets when different
  • set.isdisjoint(set2)
  • If two sets don't have the same elements , return True
  • set.issubset(set2)
  • If set yes set2 A subset of , return True
  • set.issuperset(set2)
  • If set yes set2 A superset of , return True

Set calculation

a = set('abracadabra')b = set('alacazam')print(a) # a The only letter in the dictionary # {'a', 'r', 'b', 'c', 'd'}print(a - b) # stay a Letters in , But not here. b in # {'r', 'd', 'b'}print(a | b) # stay a or b Letters in # {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}print(a & b) # stay a and b There are letters in all languages # {'a', 'c'}print(a ^ b) # stay a or b Letters in , But not at the same time a and b in # {'r', 'd', 'b', 'm', 'z', 'l'}

Set derivation

a = {x for x in 'abracadabra' if x not in 'abc'}print(a)# {'d', 'r'}

Process control

if control

if expression 1: sentence if expression 2: sentence elif expression 3: sentence else: sentence elif expression 4: sentence else: sentence 

1、 Use a colon after each condition :, Indicates the statement block to be executed after the condition is met . 2、 Use indentation to divide statement blocks , Statements with the same indentation number form a statement block together . 3、 stay Python There is no switch - case sentence .

Ternary operator :

< expression 1> if < Conditions > else < expression 2>

When writing conditional statements , Nested statements should be avoided as much as possible . Nested statements are not easy to read , And some of the possibilities may be overlooked .

for Traverse

for < Loop variable > in < Loop objects >: < sentence 1>else: < sentence 2>

else Statement in statement 2 Only the loop exits normally ( Traverse all the values in the traversal object ) When the .

When traversing through the dictionary , Keywords and corresponding values can be used items() Methods read it out at the same time :

knights = {'gallahad': 'the pure', 'robin': 'the brave'}for k, v in knights.items(): print(k, v)

When traversing through a sequence , Index location and corresponding value can be used enumerate() Function at the same time :

for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v)

Traversing two or more sequences at the same time , have access to zip() Combine :

questions = ['name', 'quest', 'favorite color']answers = ['lancelot', 'the holy grail', 'blue']for q, a in zip(questions, answers): print('What is your {0}? It is {1}.'.format(q, a))

To traverse a sequence in reverse , First specify the sequence , And then call reversed() function :

for i in reversed(range(1, 10, 2)): print(i)

To traverse a sequence in order , Use sorted() Function returns a sorted sequence , The original value is not modified :

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']for f in sorted(set(basket)): print(f)

while loop

while< Conditions >: < sentence 1>else: < sentence 2>


break Statement used in while and for In circulation ,break Statement to terminate a loop statement , That is, there is no cycle condition False The condition or sequence is not completely recursive , It also stops executing loop statements . continue Statement used in while and for In circulation ,continue A statement is used to tell Python Skip the rest of the current loop , Then proceed to the next cycle . continue Statement out of this loop , and break Out of the loop .

pass It's an empty statement , To maintain the integrity of the program structure .pass Not doing anything , Generally used as occupation statement .


  • An iterator is an object that remembers the traversal location .
  • The iterator object is accessed from the first element of the collection , Until all elements are accessed . Iterators can only move forward and not backward .
  • There are two basic ways to iterator :iter() and next().
  • character string , List or tuple objects can be used to create iterators .

Iterators can be for Loop through :

li = [1, 2, 3]it = iter(li)for val in it: print(val)

Iterators can also be used next() Function to access the value of the next element :

import sysli = [1,2,3,4]it = iter(li)while True: try: print (next(it)) except StopIteration: sys.exit()


  • stay Python in , Used yield The function of the is called the generator (generator).
  • Different from ordinary functions , A generator is a function that returns an iterator , Can only be used for iterative operations , It's easier to understand that a generator is an iterator .
  • During the call generator run , Every encounter yield Function will pause and save all current running information , return yield Value , And next time next() Method to continue from the current location .
  • Call a generator function , Returns an iterator object .

import sysdef fibonacci(n): # Generator function - Fibonacci a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1f = fibonacci(10) # f It's an iterator , Build returned by generator while True: try: print(next(f)) except StopIteration: sys.exit()


Custom function

function (Functions) It's a reusable program fragment . They allow you to name a block of code , Allows you to run code blocks anywhere in your program with this special name , And can be repeated any number of times . This is called calling (Calling) function .

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string — Used to store function descriptions .
  • Function contents start with a colon , And indent .
  • return [ expression ] End function , Optionally return a value to the caller . Without expression return It's equivalent to returning to None.
  • return Multiple values can be returned , The data returned at this time is not of tuple type .
  • When defining parameters , A parameter with a default value must follow a parameter without a default value .
def Function name ( parameter list ): The body of the function 

Parameter passing

stay Python in , Type belongs to object , Variables have no type :

a = [1,2,3]a = "Runoob"

In the above code ,[1,2,3] yes List type ,”Runoob” yes String type , Variables a There is no type , She's just a reference to an object ( A pointer ), It can point to List Type object , It can also point to String Type object .

Changeable and unchangeable objects

stay Python in , character string , Numbers and tuples are immutable objects , The list of 、 Dictionaries are modifiable objects .

  • Immutable type : Variable assignment a=5 After the assignment a=10, This is actually a new generation of int The value object 10, let a Pointing to it , and 5 To be discarded , Not change a Value , It's equivalent to a new generation of a.
  • Variable type : Variable assignment la=[1,2,3,4] After the assignment la[2]=5 Will be list la The third element value of changes , In itself la Didn't move , Only part of its internal value has been modified .

Python Parameter passing of function :

  • Immutable type : similar c++ Value transfer of , Such as Integers 、 character string 、 Tuples . Such as fun(a), It's just a Value , No impact a Object itself . For example fun(a) Internal modification a Value , Just modify another copied object , Does not affect the a In itself .
  • Variable type : similar c++ By reference , Such as list , Dictionaries . Such as fun(la), Will be la Really pass it on , After modification fun External la It will also be affected

Python Everything in is the object , Strictly speaking, we can't say value passing or reference passing , We should talk about immutable objects and mutable objects .


Required parameters

The required parameters must be passed into the function in the correct order . The number of calls must be the same as when they were declared .

Key parameters

Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in . Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names .

def print_info(name, age): " Print any incoming strings " print(" name : ", name) print(" Age : ", age) returnprint_info(age=50, name="john")

Default parameters

When you call a function , If no parameters are passed , Then the default parameters .

def print_info(name, age=35): print (" name : ", name) print (" Age : ", age) returnprint_info(age=50, name="john")print("------------------------")print_info(name="john")

Indefinite length parameter

  • With an asterisk * Will be imported as tuples , Store all unnamed variable parameters .
  • If no parameters are specified in the function call , It's just an empty tuple . We can also avoid passing unnamed variables to functions .

def print_info(arg1, *vartuple): print(" Output : ") print(arg1) for var in vartuple: print (var) returnprint_info(10)print_info(70, 60, 50)
  • Added two asterisks ** Will be imported as a dictionary . The variable name is key , Variable values are dictionary element values .

def print_info(arg1, **vardict): print(" Output : ") print(arg1) print(vardict)print_info(1, a=2, b=3)

Anonymous functions

Python Use lambda To create anonymous functions .

So called anonymity , It means to stop using def Statement defines a function in this standard form .

lambda It's just an expression , Function volume ratio def Simple a lot . lambda The subject of is an expression , Not a block of code . Only in lambda Expressions encapsulate limited logic . lambda Function has its own namespace , And can't access parameters outside their parameter list or in the global namespace . although lambda The function looks like it can only write one line , But it's not the same as C or C++ Inline function , The purpose of the latter is not to occupy stack memory when calling small functions so as to increase the running efficiency .

# Grammar format lambda [arg1 [,arg2,.....argn]]:expression

Variable scope

  • L (Local) Local scope
  • E (Enclosing) In a function other than a closure function
  • G (Global) Global scope
  • B (Built-in) Built in scope

With L –> E –> G –> B Rule search for , namely : I can't find , Then I will go to the part outside the part to find ( Such as closures ), If you can't find it, you will go to the whole situation , Then go to build in to find .

Python There are only modules in (module), class (class) And function (def、lambda) To introduce a new scope , Other code blocks ( Such as if/elif/else/、try/except、for/while etc. ) No new scopes will be introduced , In other words, the variables defined in these statements , It can also be accessed from the outside .

Variables defined within a function have a local scope , Define a global scope outside the function .

Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope .

When the internal scope wants to modify the variables of the external scope , You use global and nonlocal keyword .

num = 1def fun1(): global num # Need to use global Keyword declaration print(num) num = 123 print(num)fun1()

If you want to modify the nested scope (enclosing Scope , The outer layer is not a global scope ) The variables in the nonlocal keyword .

def outer(): num = 10 def inner(): nonlocal num # nonlocal Keyword declaration num = 100 print(num) inner() print(num)outer()


There are many ways to write modules , One of the simplest is to create a function and variable 、 With .py A file with a suffix .

Another way is to use composition Python The native language of the interpreter itself . for instance , You can use C Language to write Python modular , And after compiling , You can pass the standard Python The interpreter is in your hands Python Use them in code .

A module is a file that contains all the functions and variables you define , Its suffix is .py. Modules can be introduced by other programs , To use functions in the module . This is also used Python Standard library method .

When the interpreter encounters import sentence , If the module is in the current search path it will be imported .

The search path is a list of all directories that the interpreter will search first . If you want to import modules , You need to put the command at the top of the script .

A module can only be imported once , This prevents the import module from being executed over and over again .

The search path is stored in sys Module path Variable . The current directory refers to the directory where the program starts .

The import module

The import module :

import module1[, module2[,... moduleN]]

Import a specified part from the module into the current namespace :

from modname import name1[, name2[, ... nameN]]

Import all the contents of a module into the current namespace :

from modname import *

__name__ attribute

Each module has one __name__ attribute , When the value is '__main__' when , Indicates that the module itself is running , Otherwise it's introduced .

When a module is first introduced by another program , Its main program will run . If we want to introduce modules , A block in a module does not execute , We can use __name__ Property to make the block execute only when the module itself is running .

if __name__ == '__main__': print(' The program itself is running ')else: print(' I come from the first mock exam ')

dir function

Built in functions dir() You can find all the names defined within the module . Return as a list of strings .

If there is no given parameter , that dir() The function lists all the names currently defined .

stay Python Everything is an object ,int、str、float、list、tuple Built in data types, such as, are also classes , It can also be used. dir(int) see int All the methods involved . You can also use help(int) see int Help for class .


Package is a kind of management Python The form of the module namespace , use ” Point module name ”.

For example, the name of a module is A.B, So he means a bag A Sub modules in B .

It's like using modules , You don't have to worry about the same global variables between different modules , In the form of point module name, there is no need to worry about the duplicate names of modules between different libraries .

When importing a package ,Python Will be based on sys.path To find the subdirectories contained in this package .

The directory contains only one called Is a package , Mainly to avoid some vulgar names ( For example is called string) Carelessly affect the effective module in the search path .

In the simplest case , Put an empty one Just file it . Of course, this file can also contain some initialization code or __all__ Variable assignment .

Third-party module

  • easy_install and pip Are used to download and install Python A public resource base PyPI Of the related resource package ,pip yes easy_install Improved version , Provide better tips , Delete package And so on . The old version of python There are only easy_install, No, pip.
  • easy_install Packaging and distribution Python package ,pip It's package management .

easy_install Usage of :

  • Install a package
easy_install Package name easy_install " Package name == Version number of the package "
  • Upgrade a package
easy_install -U " Package name >= Version number of the package "

pip Usage of :

  • Install a package
pip install Package name pip install Package name == Version number of the package 
  • Upgrade a package ( If not provided version Number , Upgrade to the latest version )
pip install —upgrade Package name >= Version number of the package 
  • Delete a package
pip uninstall Package name 
  • List of installed packages
pip list


Class and object are two main aspects of object-oriented programming . One class (Class) Be able to create a new type (Type), among object (Object) It's classy example (Instance). This is the analogy : You can have types int The variable of , That is to say, the variable that stores integers is int Class ( object ).

  • class (Class): A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class .
  • Method : Functions defined in class .
  • Class variables : Class variables are common to the entire instantiated object . Class variables are defined in the class and outside the function body . Class variables are usually not used as instance variables .
  • Data member : Class variables or instance variables are used to process data related to a class and its instance objects .
  • Method rewriting : If the method inherited from the parent class does not meet the needs of the child class , It can be rewritten , This process is called method coverage (override), Also known as method rewriting .
  • Instance variables : Variables defined in methods , Class that only works on the current instance .
  • Inherit : That is, a derived class (derived class) Inherited base class (base class) Fields and methods for . Inheritance also allows the object of a derived class to be treated as a base class object . for example , There is such a design : One Dog Object of type derived from Animal class , This is a simulation ” It's a (is-a)” Relationship ( Case diagram ,Dog It's a Animal).
  • Instantiation : Create an instance of a class , Class specific objects .
  • object : Data structure instance defined by class . Object contains two data members ( Class variables and instance variables ) And methods .

Python The classes in provide all the basic functions of object-oriented programming : Class inheritance mechanism allows multiple base classes , Derived classes can override any method in the base class , Method can call a method with the same name in the base class .

Objects can contain any number and type of data .


self Represents the current instance , Represents the address of the current object . Class by self.__class__ Express .

self Not a keyword , Other names can also be substituted , but self It is a common standard name .


Class by class Keyword to create . After class instantiation , You can use its properties , actually , After creating a class , You can access its properties through the class name .

Object methods

Method by def Keyword definition , Different from functions , Method must contain parameters self, And it's the first parameter ,self Represents an instance of this class .

Class method

Decorator @classmethod Methods can be identified as class methods . The first parameter of a class method must be cls, Instead of self.

Static methods

Decorator @staticmethod Methods can be identified as static . The first parameter of the static method is no longer specified , I don't need to self or cls.

__init__ Method

__init__ Method is construction method , Will run first when the object of the class is instantiated , You can put the initialization operation into this method .

If I rewrite it __init__, Instantiating a subclass does not call what the parent class has already defined __init__.


Class variables (Class Variable) Is Shared (Shared)—— They can be accessed by all instances belonging to the class . This type of variable has only one copy , When any object changes a class variable , The changes will be reflected in all other instances .

Object variables (Object variable) Owned by each individual object or instance of a class . under these circumstances , Each object has a copy of its own field , in other words , They will not be shared , It is not associated in any way with fields of the same name in other different instances .

stay Python in , Variable names are similar to __xxx__ Of , It starts with a double underline , And ends with double underscores , It's a special variable , Special variables are directly accessible , No private Variable , therefore , Out-of-service __name__、__score__ Such variable names .

Access control

  • Private property
  • __private_attr: Start with two underscores , Declare the property private , Can't be used or directly accessed outside the class ground .
  • Private method
  • __private_method: Start with two underscores , Declare the method private , Can only be called inside a class , Cannot be called outside a class ground .

We also believe that the agreement , A property or method that begins with an underline is protected . such as ,_protected_attr、_protected_method.


Class can inherit , It also supports inheriting multiple parent classes . When defining a class , The bracket after the class name specifies the parent class to inherit , Multiple parent classes are separated by commas .

Instances of subclasses have full access to all non private properties and methods of the inherited parent class .

If the parent class has the same method name , When subclass is used, it does not specify ,Python Search from left to right , When the method is not found in the subclass , From left to right, find whether the parent class contains methods .

Method rewriting

Subclass methods can override parent methods . Overridden method parameters do not enforce consistency , But reasonable design should be consistent .

super() Function can call a method of the parent class , The problem of multiple inheritance .

Class :

  • __init__: Constructors , Call... When the object is generated
  • __del__: Destructor , Use... When releasing objects
  • __repr__: Print , transformation
  • __setitem__: Assign values according to the index
  • __getitem__: Get values by index
  • __len__: Get the length
  • __cmp__: Comparison operations
  • __call__: Function call
  • __add__: Add operation
  • __sub__: Subtraction operation
  • __mul__: Multiplication
  • __div__: In addition to the operation
  • __mod__: The remainder
  • __pow__: chengfang

Class also supports overloading .


class Person: """ Personnel information """ # full name ( Common property ) name = '' # Age ( Common property ) age = 0 def __init__(self, name='', age=0): = name self.age = age # Overloading proprietary methods : __str__ def __str__(self): return " It's overloaded here __str__ Proprietary methods , " + str({'name':, 'age': self.age}) def set_age(self, age): self.age = ageclass Account: """ Account information """ # The account balance ( Private property ) __balance = 0 # Total amount of all accounts __total_balance = 0 # Get account balance # self Must be the first parameter of the method def balance(self): return self.__balance # Increase account balance def balance_add(self, cost): # self This example is visited self.__balance += cost # self.__class__ You can access classes self.__class__.__total_balance += cost # Class method ( use @classmethod identification , The first parameter is zero cls) @classmethod def total_balance(cls): return cls.__total_balance # Static methods ( use @staticmethod identification , No class or instance parameters are required ) @staticmethod def exchange(a, b): return b, aclass Teacher(Person, Account): """ Teachers' """ # Class name _class_name = '' def __init__(self, name): # The first overload parent class __init__() Construction method # super( Subclass ,self).__init__( Parameters 1, Parameters 2,....) super(Teacher, self).__init__(name) def get_info(self): # Return personal information in the form of a dictionary return { 'name':, # The parent class is accessed here Person The attribute value 'age': self.age, 'class_name': self._class_name, 'balance': self.balance(), # The method called here is overloaded by subclass } # Method overloading def balance(self): # Account.__balance For private property , Subclass cannot access , So the parent class provides methods to access return Account.balance(self) * 1.1class Student(Person, Account): """ Student """ _teacher_name = '' def __init__(self, name, age=18): # The second overload parent class __init__() Construction method # Parent class name .__init__(self, Parameters 1, Parameters 2,...) Person.__init__(self, name, age) def get_info(self): # Return personal information in the form of a dictionary return { 'name':, # The parent class is accessed here Person The attribute value 'age': self.age, 'teacher_name': self._teacher_name, 'balance': self.balance(), }# Teachers' Johnjohn = Teacher('John')john.balance_add(20)john.set_age(36) # An instance of a subclass can directly call the method of the parent class print("John's info:", john.get_info())# Student Marymary = Student('Mary', 18)mary.balance_add(18)print("Mary's info:", mary.get_info())# Student Fakefake = Student('Fake')fake.balance_add(30)print("Fake's info", fake.get_info())# There are three different ways to call static methods print("'a', 'b'):",'a', 'b'))print(', 2)',, 2))print(', 20):',, 20))# Class method 、 Class properties print('Account.total_balance():', Account.total_balance())print('Teacher.total_balance():', Teacher.total_balance())print('Student.total_balance():', Student.total_balance())# Overloading proprietary methods print(fake)

Output :

John's info: {'name': 'John', 'age': 36, 'class_name': '', 'balance': 22.0}Mary's info: {'name': 'Mary', 'age': 18, 'teacher_name': '', 'balance': 18}Fake's info {'name': 'Fake', 'age': 18, 'teacher_name': '', 'balance': 30}'a', 'b'): ('b', 'a'), 2) (2, 1), 20): (20, 10)Account.total_balance(): 0Teacher.total_balance(): 20Student.total_balance(): 48 It's overloaded here __str__ Proprietary methods , {'name': 'Fake', 'age': 18}

Errors and exceptions

Grammar mistakes

SyntaxError Class representation syntax error , An error that triggers when the interpreter finds that the code fails the syntax check . Grammatical errors are useless try...except... The captured .

>>> print: File "<stdin>", line 1 print: ^SyntaxError: invalid syntax


Even if the syntax of the program is correct , When it's running , There is also the possibility of mistakes . An error that occurs at run time is called an exception . The first part of the error message shows the context in which the exception occurred , And display the specific information in the form of call stack .

>>> 1 + '0'Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'int' and 'str'

exception handling

Python Provides try ... except ... To capture and handle exceptions .

try Statement execution process is as follows :

Python 3 introduction , Just read this one

  • First , perform try Clause ( In keywords try And keywords except The sentence between )
  • If no exceptions occur , Ignore except Clause ,try End after Clause execution .
  • If in execution try An exception occurred during clause , that try The rest of the clause will be ignored . If the type of exception and except The following names match , So the corresponding except Clause will be executed . Finally, execute try Code after statement .
  • If an exception is not associated with anything except matching , Then this exception will be passed to the upper level try in .
  • One try The statement may contain more than one except Clause , To handle different specific exceptions .
  • At most one except Clause will be executed .
  • The handler will only target the corresponding try Exception in Clause , Not the others try Exception in handler for .
  • One except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple .
  • the last one except Clause to ignore the name of the exception , It will be used as a wildcard . You can use this method to print an error message , Then throw the exception again .
  • try except There is also an optional else Clause , If you use this clause , Then it must be put on all except After Clause . This clause will be in try Clause is executed when no exception occurs .
  • Exception handling doesn't just deal with those that happen directly in try Exception in clause , It can also handle functions invoked in clauses ( Even indirectly called functions ) The exception thrown in .
  • No matter try Is there any exception in the clause ,finally Clause will execute .
  • If an exception is in try In Clause ( Or in except and else In Clause ) To be thrown out , And nothing except Stop it , So this exception will be in finally Clause is thrown again after execution .

Throw an exception

Use raise Statement throws a specified exception .

raise The only parameter that specifies the exception to be thrown . It must be an exception instance or an exception class ( That is to say Exception Subclasses of ).

If you just want to know if this throws an exception , Don't want to deal with it , So a simple raise Statement can throw it out again .

Custom exception

You can have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly .

When it is possible to create a module to throw many different exceptions , One common approach is to create a base exception class for this package , Then create different subclasses for different error situations based on this base class .

Most of the names of exceptions are ”Error” ending , It's the same as the standard exception naming .


import sysclass Error(Exception): """Base class for exceptions in this module.""" pass# Custom exception class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, message): self.expression = expression self.message = messagetry: print('code start running...') raise InputError('input()', 'input error') # ValueError int('a') # TypeError s = 1 + 'a' dit = {'name': 'john'} # KeyError print(dit['1'])except InputError as ex: print("InputError:", ex.message)except TypeError as ex: print('TypeError:', ex.args) passexcept (KeyError, IndexError) as ex: """ Support handling multiple exceptions at the same time , Put parentheses in tuples """ print(sys.exc_info())except: """ Catch other unspecified exceptions """ print("Unexpected error:", sys.exc_info()[0]) # raise Used to throw an exception raise RuntimeError('RuntimeError')else: """ When there is no exception , Will execute else Clause """ print('"else" Clause ...')finally: """ Whether it's abnormal or not , Will carry out finally""" print('finally, ending')

File operations

Open file

open() Function is used to open / Create a file , And return a file object :

open(filename, mode)
  • filename: String value containing the name of the file you want to access
  • mode: Determines the mode of opening files : read-only , write in , Supplemental

File open mode :

Python 3 introduction , Just read this one

File object method

  • fileObject.close()
  • close() Method to close an open file . The closed file can no longer be read or written , Otherwise it will trigger ValueError error . close() Method allows multiple calls .
  • When file object , When referenced to another file ,Python It will automatically close the previous one file object . Use close() Method to close a file is a good habit .
  • fileObject.flush()
  • flush() Method is used to flush the buffer , Write the data in the buffer to the file immediately , Clear the buffer at the same time , No need to wait passively for the output buffer to write .
  • In general , The buffer will be refreshed automatically after the file is closed , But sometimes you need to refresh it before closing , It can be used at this time flush() Method .
  • fileObject.fileno()
  • fileno() Method returns an integer file descriptor (file descriptor FD integer ), Available for the underlying operating system I/O operation .
  • fileObject.isatty()
  • isatty() Method to detect whether the file is connected to a terminal device , If it's a return True, Otherwise return to False.
  • next(iterator[,default])
  • Python 3 Medium File Object does not support next() Method . Python 3 Built in functions for next() Calling through iterators __next__() Method to return to the next item . In circulation ,next() The function is called in every loop. , This method returns the next line of the file , If the end is reached (EOF), The trigger StopIteration.
  • read() Method to read a specified number of bytes from a file , Read all if not given or negative .
  • fileObject.readline()
Share the :
Copyright notice : Content of this page ( Including but not limited to words 、 picture 、 video ) Spontaneous contribution by Internet users , This article only represents the author himself . This site only provides information storage space service , No ownership , No legal liability . If we find that the site is suspected of plagiarism infringement / Contents of violation of laws and regulations , Please send an email to report , Once verified , This site will be deleted immediately .

existing 15 Ginseng and

Comment on

Related to recommend

TA The article
  • Hot news today
  • This week's hot article
  • Hot news this month
Small make up recommend     
Hot search      more >>>
本文为[Light ink green shirt]所创,转载请带上原文链接,感谢

  1. Python pandas: using pandas to add row data, that is, adding dictionary data to dataframe according to row data cycle
  2. Python:将Flask测试应用部署到Deta
  3. Python:OAuth2第三方登录之Github
  4. Python:使用pydantic库进行数据校验
  5. Python:免费IP归属地查询接口
  6. Python:使用user-agents库解析浏览器信息
  7. Python:cached_property缓存对象的属性
  8. Python:打包配置文件 详解
  9. Python:ORM(Object Relational Mapper)模块汇总整理
  10. Python:datetime时间UTC时间转东八区
  11. Python: deploying flash test application to deta
  12. Python: oauth2 GitHub for third party login
  13. Python: using pydantic library for data verification
  14. Python: free IP home location query interface
  15. Python: parsing browser information using user agents Library
  16. Python:cached_ Property to cache the properties of an object
  17. Python: packaging configuration files Detailed explanation
  18. Python: ORM (object relational mapper) module summary
  19. Python: datetime, UTC, turn to District 8, East
  20. python tkinter 将某一目录下的所有图片插入到docx文件中
  21. Python Tkinter inserts all the pictures in a directory into the docx file
  22. 解决忽略VScode中Python插件pylint报错的问题
  23. To solve the problem of ignoring the error of Python plug-in in vscode
  24. python 毫秒级时间,时间戳转换
  25. Python millisecond time, timestamp conversion
  26. python try except 出现异常时,except 中如何返回异常的信息字符串
  27. When an exception occurs in Python try except, how to return the exception information string in except
  28. 手机最强Python编程神器,在手机上运行Python
  29. The strongest Python Programming artifact on mobile phones, running Python on mobile phones
  30. 2021年Python程序员薪资待遇如何?
  31. 「python安装」Windows上安装和创建python开发环境
  32. What is the salary of Python programmers in 2021?
  33. "Python installation" to install and create a python development environment on Windows
  34. python解决组合问题
  35. Python to solve the problem of composition
  36. Python中的Lasso回归之最小角算法LARS
  37. Lars, the least angle algorithm of lasso regression in Python
  38. 利用python提取网站曲线图数据
  39. Using Python to extract website graph data
  40. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
  41. Detailed usage of urllib in Python 3 (header, proxy, timeout, authentication, exception handling)
  42. python 第三方库paramiko
  43. python 第三方库paramiko
  44. Python third party library paramiko
  45. Python third party library paramiko
  46. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  47. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  48. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  49. django学习-27.admin管理后台里:对列表展示页面的数据展示进行相关优化
  50. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  51. Django learning - 27. Admin management background: optimize the data display of the list display page
  52. python day2
  53. python day2
  54. Python 内存泄漏问题排查
  55. Troubleshooting of Python memory leak
  56. Python 与 excel的简单应用
  57. Simple application of Python and excel
  58. Python 与 excel的简单应用
  59. Simple application of Python and excel
  60. 2.7万 Star!最全面的 Python 设计模式集合