Study Python
Content ! Learning links on the official website
{}
To distinguish between Version is Python3.10
python3
Will go directly to a python Interpreter ,python The interpreter can be used to directly execute a python file (python Can be like other languages , Put it in a file to write ), It's like writing shell
Script .python3 file name .py
./ file name .py
, The file needs to have executable permissions , If not implemented :chmod +x file name .py
#
, The comment statement is on a separate line , Or two spaces after a statement tab
key )exit()
Or shortcut key ctrl+d
Numbers
/
: The default is floating-point division ,//
: to be divisible by , yes Rounding down (-1 // 3 ( Is minus one third ), Rounded down to -1).C++ The integral division of is rounding to zero (-1 / 3 Is minus one third , Round to zero )**
: Multiplication n = 20
, Note that if the variable is not assigned a value, it cannot be used directly a, b = b, a
_
Represents the value of the previous expression character string
character string :python
String and C++
In the same way , The difference lies in python
Both single and double quotation marks can represent strings , There is no difference between .python
The string in cannot be modified
Subscript :
-
Represents a number from right to left , From right to left When counting, subscript from 1
Start . No addition -
, Express From left to right Count , Subscript from 0
Start section
word[0:2]
0
, Omit the following , The default is string length .word[:2] word[4:]
word[-2:] word[-5,4]
word[:2] + word[2:]
len
: You can find the length of all types
analogy C++ In the array . Use brackets ([]
) Express , Use commas for each element (,
) separate , The type of each element in the array can be different
a = [1, 4, 9]
b = [1, 2.0, 'yjx', [2,3]]
x, y, z = a
You can access elements by subscript , Support slicing operation . Element supports modification , Unlike strings .x[0] = 4
,x[1:3] = ['a', 'b']
Shallow copy
Add operation is supported , The effect is to splice the two arrays together
Additive elements :a.append(6)
perhaps a += [7]
, Add elements at the end of the list
len(a)
: Ask for a list a
The length of ,sroted(a)
: Sort list
x[:] = []
,[]: empty . Empty an array
Two dimensional array : Lists are nested , It's a two-dimensional array ,x = [[1,2], [3,4]]
a, b = 0, 1
python Support compound assignment : The first term is assigned to the first variable , The second term is assigned to the second variable , And so on …
>>> x = int(input("Please enter an integer: ")) # Read in an integer , adopt int Function to convert a string to an integer
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
python Medium for loop : There's a bunch of things , adopt for Loop through enumerations one by one , Arithmetic operators are not supported , Can't directly implement things like C++ Medium for (Int i = 0; i < 10; i ++)
Such operation
Loop through a list
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
Loop through a dictionary
use range To implement a common for loop range()
: Will return a Left closed right away The range of
for i in range(0, 10)
print(i)
range
Reverse order can be achieved :range(9, -1, -1)
, The third parameter is tolerance
When there is only one parameter :range(10)
: The default is equivalent to range(0, 10)
f = g
, among g
and f
It's all functions *
, Expand the elements in the list into several variables separated by commas , Parameters assigned to the function , Call... As an argument to a function . Unpack a list with *
, Unpacking a dictionary is to use **
list
b = [i *i for i in range(10)] # b Every element in it is i*i,i Is the enumeration [0,9]
Tuples
a(1, 2, 3)
, Notice the use of parentheses , The list is in square brackets . Similar to list operation , The only difference is that the elements in the list can be modified , Elements in tuples cannot be modified b = (1, 2, 3)
, Brackets can be omitted :b = 1, 2, 3
. You can also assign a tuple to several variables in reverse :x, y, z = b
, among x = 1 y = 2 z = 3
( Unpacking operation )y, x = x, y
aggregate (set)
Analogy to C++ Of set
a = se()
, a = {1, 2, 3}
,{}
It can represent either a collection or a dictionary , The distinction mainly depends on what is stored in it key-value Yes or a separate value , If it is key-val Yes, that's the dictionary , If it is a single value, then it is aggregate a.add(1)
. Only one of the same elements is reserved , If the newly inserted element appears in the collection , Then the new element will not be inserted into the collection a = {
1,2,2,3,5}
set(a) # The result is the set after de duplication
a = list(set(a)) # The result after de duplication is still a list type
Dictionaries (dict)
tel = {'jack':4096,'sape':4139}
tel['jack'] = 8888
Why modules are needed ? answer : It is difficult to debug a large project if all the contents are written into one file , You need to split a huge project into several modules . Adopt tree structure in project development , Each folder represents a module .
Introduce a self defined module , Reference... In other documents from File path (. spaced ) import file / function / class
, When introducing multiple , For each ,
separate
When introducing a function and renaming
from File path import function 1 as Alias , function 2 as Alias
python A large number of modules have been implemented in , Directly after installation import Just come in
print
Formatted string ,% ()
: Pass in the corresponding parameter , It can be like C++ Same format output fin.read()
Read all contents of the file
fin.readlines()
Read all lines , Will return a list
Read in line by line
effect : When you open a website 502
When it's wrong ,502
An error is an exception in the program , Will catch the exception , Users will not see 502
You will jump to a 404
page
def divide(x, y):
try: # Try to execute the contents of this code block
res = x/y
except Exception as e: # If there is an anomaly , Do the following
print(str(e)) ## Direct output exception , There is no error in the procedure , The program is still running normally , If you do not use exception handling , After the operation, the subsequent program will not be executed
else: # If nothing unusual happens , Content that does not execute exception handling , Will execute else Contents of Li
print("result is", res)
finally: # The following will be executed regardless of whether an exception occurs , It is usually used to close the database
print("executing finally clause")
__self__init(self):
Intrinsic function , Be similar to C++ Middle constructor , Be careful self Be sure to write , Arguments can also be passed into the constructor .python The member variables in are written in the function ,C++ The member variables in are written outside the function .python Classes and functions are used in the same way a = Car()
: Instantiate an object ,update
: Member functions ,a
: Member variables
2. Inherit ( Parenthesis )