Consolidate some simple codes before the exam.
I wish everyone can pass, excellent!!
catalogue
4. abs() absolute value divmod() Division pow() Power max min Min
5. Bit operation & | ^ ~ It should be a multiple-choice question
17. Dimensions of data organization
24. Overview of Python third-party libraries
1. Simple output
print('Hello world!')
2. for loop
for i in range(10): if i%2==0: continue print(i)
3,eval() Dequote
a=input("Please enter your name:") #Accept tpye(a) according to the character type b=eval(input("Please enter your age: ")) #eval dequote print("This is a string.") print(a,b) print("You are?{} ,you{}Yes".format(a,b))
4. abs() absolute value divmod() Division pow() Power max min Min
print(abs(-25)) #absolute value print(divmod(10,3)) #Divide to get cells (3, 1) x,y=divmod(10,3) #Unpacking assignment cell print(x,y,"\n") print("pow(10,2)={}".format(pow(10,2)) ) #Calculate the y-power of x print("pow(10,2,3)={}\n".format(pow(10,2,3)) ) #Calculate the y-power of x and take the remainder 3 print("max(1,2,3,4,6,4,8,9)={}".format(max(1,2,3,4,6,4,8,9))) print("min(1,2,3,4,6,4,8,9)={}".format(min(1,2,3,4,6,4,8,9)))
5. Bit operation & | ^ ~ It should be a multiple-choice question
x=0b10101111 y=0b11111110 #One can be considered an opcode print("0b10101111&0b11111110={}\n".format(bin(x&y)))#Bitwise and, 1 unchanged, 0 cleared print("0b10101111|0b11111110={}\n".format(bin(x|y))) #Press bit or, 1 full 1, 0 unchanged print("~0b10101111={}\n".format(bin(~x))) #Reverse by bit - 0b1011000 print("0b10101111^0b11111111={}\n".format(bin(x^y))) #By bit or, the use is unknown print("0b10101111<<2={}".format(bin(x<<2))) #Shift left print(x) print("x<<2={}\n".format(x,x<<2)) #Shift left, shift left 1 bit, double print("0b10101111>>2={}".format(bin(x>>2))) #Shift right with symbol
6. Escape character
print("123\n456") # \n line feed print("123\t456") # \t tab 4 spaces print("123\b") # \b backspace
7. Slice
Index with [], excluding the second bit,
Note that starting from bit 0
s='Computer level II Examination' print(s[0:2]) print(s[-1:2]) #No result print(s[-1:2:-1]) #The result is grade two
8. Format output
Formatted output is most likely an operation problem,
s=eval(input("Please enter a string:")) print("{:->20,}".format(s))
To remember the position of the format, fill it first, then left and right, and then width
Chang Kao
For example: character class:
s='python' print("{:*<20}".format(s)) #*Fill, left justified, 20 characters print("{:\^20}".format(s)) # \Fill, center, 20 characters print("{:.5}".format(s)) #Keep only the first 5 characters result: Python
{} is a placeholder and must be added, otherwise it is an ordinary string ":. 5"
It is mainly to fill in some characters for output
Digital class:
print("{:5,}".format(456789123)) #Width 5 (useful only if less than 5), comma separated result: 456789123 print("{0:b},{0:c}, {0:d}, {0:o}, {0:x}, {0:X}".format(520)) # Binary, Unicode character, decimal, octal, hexadecimal, hexadecimal #1000001000, Ȉ, 520, 1010, 208, 208 print("{0:e}, {0:E}, {0:f}, {0:%}".format(3.1415926)) #E exponential form e exponential form standard floating point form percentage form of floating point number #3.141593e+00, 3.141593E+00, 3.141593, 314.159260% print("{0:.2f}".format(3.1415926)) #Save two decimal places result: 3.14
9. String
Single string operation
s='Hello World' print(str(s)) #Force type conversion to str print(len(s)) #String length print(s.count('or'),'\n') #Number substring print(s.lower()) #All lowercase, unchanged s print(s.upper(),'\n') #All uppercase, without changing s, only when s = s.upper() print(s.replace("He",'hh')) #he is replaced by hh and s remains unchanged print(s.center(15,"*"),'\n') #String centering function, fillchar parameter optional print(s.split(' ')) #Returns a list with sep as the separation point, and sep is blank by default print(s.strip("H")) #Removes the characters listed in chars to the left and right of the string str print(s.join("123"),'\n') #Insert s as a separator into "123". Generally, s is like ',' print(s) #s hasn't changed
Inter string operation
a='python' b='520' print(a+b) #String connection print(b*2) #String copy print(a in b) #Does the string exist in
In particular, split(),strip(),join() is often used in operation questions
Chapter IV:
10. for loop
for loop variable in Combined variables (string, file, range() function, list, dictionary): (don't forget the colon)
for i in range(1,4): print(i)
1.continue statement
Used to end the current loop, that is, jump out of the following unexecuted statements in the loop body, but do not jump out of the current loop.
2.break statement
Jump out of the innermost loop. After terminating the loop, continue execution from the code after the loop.
11. Exception handling
Single branch selection structure. The usage syntax is:
s=input('Please input number:') while 1: try: s=int(s) print(s) break except ValueError: print("a number!! ") s=input("Please input number:")
try...except...else...
This structure can be regarded as a double branch structure,
The code in else is executed only when the code in try does not throw an exception.
try...except...finally...
In this structure, no matter whether an exception occurs in the try code or not, the code in the finally statement block will always be executed.
Exception handling structure for capturing multiple exceptions
try:
<>
Exception < exception type >:
< Operation >
Exception < exception type >:
< Operation >
Common errors
- ZeroDivisionError: division by zero # division error
- TypeError: Can't convert 'int' object to str implicitly Program exception handling
- TypeError: unsupported operand type(s) for *: 'set' and 'int' Operation type is not supported
- NameError: name 'name' is not defined Variable name does not exist
- FileNotFoundError: [Errno 2] No such file or directory: 'wangyan.txt' file does not exist
- TypeError: object of type 'int' has no len() Parameter type mismatch
Chapter V: combination type
12. List
- A pair[ ] Inside, separated by commas;
- There is no length limit, element types can be different, and predefined lengths are not required
- Elements are in order, and indexes can be used
- Linear data structure
- The list is variable
Create list
a_list=[1,'python',[5,2,0]] #Create list directly print(a_list) s='python' s_list=list(s) #The list() function converts the iteratable object into a list (string) print(s_list)
ls=['book',23,[2010,'stud1'],20] #Multilist nested list print(ls[2][1][-1])
List operation method
s=list('woaiwangbingbing') print(s)
The following code is manually copied into the IDLE Shell to run
s.count('a') #Methods are followed by arguments, and () must have arguments s.index('a',0,10) #The first occurrence of the corner sign of the 'a' element, search from 0 to 10 s.append("h") #The return value is none, indicating that it is modified locally and s has been changed s.insert(-1,"0") #If the return value is none, it means that it is modified locally. Finally, only the last bit can be pushed back, which is complementary to append s.extend([1,2,3]) #Modify in place, which is equivalent to multiple append del s[0] #Delete function s.remove('a') #From left to right, delete an a s.pop(0) #Show s[0] and delete it from the list s.reverse() #Modify in place, reverse order s.clear() #clear list s.sort(key=None,reverse=True) #No sort, flip s.copy() #Copy all elements in the list
List operator
x=[1,2,3] print(x) #[1, 2, 3] x=x+[4] #You can add a list directly print(x) #[1, 2, 3, 4] x+=[5] #Self addition is also OK print(x) #[1, 2, 3, 4, 5] x=x*2 print(x) #[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
List related examples
a = [[1,2,3], [4,5,6], [7,8,9]] s = 0 for c in a: #c is an iterative variable, which is equal to [1,2,3], [4,5,6], [7,8,9] respectively for j in range(3): #j add the elements in c from 0, 1 and 2 s += c[j] print(s) #So this is a double ergodic summation
13. tuple
- All elements are placed in parentheses ();
- If there is only one element, a comma must be added at the end, otherwise it will form a number instead of a tuple
- Creating empty tuples using tuples
- Support bi-directional indexing
- Tuples can be keys to dictionaries
- Tuples are immutable
Tuple creation
x=(1,2,3) print(x[-1]) try : x[1]=1 except TypeError: print('Tuple cannot change a value')
14. Dictionary
- dict() generates an empty dictionary
- A collection of keys and values connected by colons
- Key value pairs have no order and cannot be repeated
- Element types can be different
- Use curly braces{ } express
- The dictionary is stored as key value pairs, so the key is the index of the value
- Dictionaries are variable and can store any type
Establishment of dictionary
d=dict() d={'name':'jack','age':'18','gender':'man'}
Dictionary lookup
d={'name':'jack','age':'18','gender':'man'} print(d['name']) Direct search key, with[ ] try: d['123'] except KeyError: print("No key value pair") print(d.keys()) #Return key, list form print(d.values()) #Return value print(d.items()) #Return key value, primitive form print(d.get('key','default')) #Check the key. If no value of defaul is returned, note that quotation marks must be added
Dictionary deletion
d={'name':'jack','age':'18','gender':'man'} print(d.clear()) #Empty dictionary print(d.popitem()) #Randomly take a key value pair (cell form) and delete it print(d.pop(key,default)) #If the key exists, the corresponding value is returned, and the key value pair is deleted. Otherwise, the default value is returned
15. set {,}
- The elements in the collection are not repeatable
- Type can only be immutable
- Collection elements have no order and cannot be compared or sorted
- Curly braces {} indicate that there is no concept of index and location
- Can be created using set()
Set establishment
s={101,'python',23.2} s=set() s=set((1,2,5,4,2,1,4,3)) #lack order
Operation of collection
s={1,2,3,4,5} t={3,4,5,6,7} print(s-t) #Only {1, 2} print(s&t) #Hand in {3, 4, 5} print(s^t) #Respective special {1, 2, 6, 7} print(s|t) #And {1, 2, 3, 4, 5, 6, 7}
The following code is manually copied into the IDLE Shell to run
s.add(x) #Add element x s.remove(x) #Delete x, if none, KeyError exception s.clear() #Delete all, return to None and change locally s.update( ) #Add a new element, return to None, and change it locally s.pop() #Randomly delete and return an element of the collection x in s #x is in the s set, judgment statement x not in s s.discard(x) #Specific delete x
Chapter VI: Documents
16. Documents
File type: text file, binary file
File opening method:
Open mode | meaning |
'r' | Read only mode. If the file does not exist, an exception FileNotFoundError is returned |
'w' | Overwrite the write mode. If the file does not exist, it will be created. If it exists, it will be overwritten |
'x' | Create a write mode. If the file does not exist, it will be created. If it exists, an exception FileExistsError will be returned |
'a' | Append write mode. If the file does not exist, it will be created. If it exists, the content will be appended at the end of the file |
'b' | Binary file mode |
't' | Text file mode |
'+' | It is used with r/w/x/a to add simultaneous reading and writing function on the basis of the original function |
File operation
f=open('chapter6.txt','r') #Open the file. Note that you must have a to open it txt = f.read() #read txt_l = f.readline() #Read a line txt_ls = f.readlines() #Read in all rows to form a list for each behavior element f.close() f=open('chapter6.txt','w') #Open the file. Note that you must have a to open it f.write(txt) #write f.writelines(txt_ls) #Write by list f.close()
17. Dimensions of data organization
csv data format
''' One dimensional data: one dimensional data is composed of ordered or disordered data with equal relationship,
It is organized in a linear manner, corresponding to the concept of array in mathematics. ''
'''
Storage of one-dimensional data: separate the data with spaces, commas, line breaks or other symbols,
The comma separated storage format is called CSV format. ''
ls=['Tiananmen','the Imperial Palace','Jiuhua Mountain','Mount Huangshan'] fo=open('visity.csv','w') fo.write(','.join(ls)) fo.close() fi=open('visity.csv','r') ls2=fi.read().strip('\n').split(',') #strip removes' \ n 'on both sides, and split s are separated by', 'to form a list print(ls2) fi.close()
two-dimensional
ls=[['scenic spot','Ticket Price'],['Tiananmen','15'],['the Imperial Palace','120'],['Jiuhua Mountain','160']] fo=open('ticket.csv','w') for row in ls : fo.write(','.join(row)+'\n') fo.close() fi = open('ticket.csv','r') ls2=[] for line in fi: ls2.append(line.strip('\n').split(',')) fi.close() print(ls2)
#High dimensional data
'''
High dimensional data is composed of key value pair type data, which is organized in object mode and can be nested at multiple levels.
High dimensional data derives the syntax structure of specific data organizations such as HTML, XML and JSON.
'''
Chapter 7: function
18. Functions
#1 definition of function
def interchange(a,b): print(b,a) interchange(1,3)
#2 functions with default values
- When using the formal parameter name, the parameter transfer order can be adjusted arbitrarily.
- Positional parameters must be passed in before keyword parameters.
- Position parameters cannot appear on the right of any default value parameter.
- The function is called multiple times and parameters are not passed for the default value parameter. The default value parameter is interpreted and initialized only once during definition.
def data(name,age=18): #The default value can only be on the far right print(name+str(age)+'year') data('Zhang San',126) data('Li Si',26)
#3 keyword parameter transfer
def data(name,age=18): #The default value can only be on the far right print(name+str(age)+'year') data(age=180,name='Zhang San') #Keyword parameter transfer, and the parameter transfer order can be adjusted arbitrarily
#4 variable length parameters*
*Param and * * param
- *param receives any number of parameters in a tuple
- **param receives any number of keyword parameters and puts them into the dictionary
def demo(*p): #The feeling of the pointer print(p) demo(1,2,'t') #Results: (1, 2,'t ') def demo1(**p): #Reflect mapping relationship print(p) demo1(a=1,b=2,c=3) #Result: {a ': 1,' B ': 2,' C ': 3}
#5 sequence unpacking when passing parameters*
def demo(a,b,c): print(a*b*c) lis = [2,3,4] demo(*lis) #Unpacking assignment #demo([2,3,4]) #This won't work because it's actually a parameter tup = (3,4,5) demo(*tup) #Tuples can also be unpacked dic={1:'a',2:'b',3:'c'} demo(*dic) #Unpack dictionary keys def demo(a,b,c): print(a+b+c) demo(*dic.values()) #Unpack dictionary values set = {4,5,6} demo(*set) #Unpack collection
#6. Unpack the dictionary and transfer it to keyword reference
p={'a':1,'b':2,'c':3} def f(a,b,c): #All keys in the dictionary must be formal parameter names of functions or correspond to two * variable length parameters. print(a,b,c) f(**p) #Results: 1 2 3 ''' #It is equivalent to passing a = 1, B = 2 and C = 3, which is a bit like keyword assignment ''' def f(**p): for i in p.items(): print(i) p={'x':1,'y':2,'z':3} f(**p) #Result: ('x', 1) # ('y', 2) # ('z', 3)
- Multiple position variable parameters use an asterisk * in front of the formal parameter;
- Multiple keyword variable parameters use two asterisks * * in front of the formal parameter;
- Position variable parameters and keyword parameters can collect several arguments, multiple position variable parameters can be collected to form a tuple, and multiple keyword variable parameters can be collected to form a dict;
- When mixed parameters are used, variable length parameters should be placed at the end of the parameter list, ordinary parameters should be placed in front of the parameter list, and position variable parameters should be placed before keyword variable parameters.
#7 the formal parameters in the function have nothing to do with the external arguments
def func(a,b): c=a**2+b b=a return c a=10 b=100 c=func(a,b)+a print('a=',a) #a= 10 print('b=',b) #b It is not changed due to the assignment in the function #b= 100 print('c=',c) #c= 210
#8 function return value
- The return statement is used to end the function and return the program to the location where the function is called to continue execution;
- The return statement can appear in any part of the function;
- It can return the results of 0 or more function operations to the variable where the function is called at the same time;
- When return returns multiple values, the returned values form a tuple data type.
def cal(x,y): return x+y,x*y print( cal(4,6) ) #return when multiple values are returned, they are in the form of cells. Obviously, they can't be changed. It's reasonable (10, 24) a,b = cal(4,6) print(a,b) 10 24
#9 scope of function
Local variables:
- Naming rules are the same as identifiers
- It is defined inside the function and is only valid inside the function. It is destroyed when the function exits
Global variables:
- Naming rules are the same as identifiers
- When a global variable is used inside a function, it needs to be declared with the global keyword, which has the same name as the global variable of the external variable
- Variables defined outside the function are valid throughout the execution of the program
def demo(): global x #Use externally defined variables x = 3 y = 4 print(x,y) #x=6 #If it is not defined externally, it is defined internally demo() # print(y) #A function defined within a function cannot be used outside. An error is reported
x=3 def demo(): print(x)#Exception. When global is not used in the function, it cannot be operated on x=x+1 # print(x) demo()
#When a local variable has the same name as a global variable, the local variable will temporarily hide the global variable with the same name in its scope.
x=3 def demo(): x=6 print(x) demo() #Output local variable 6 instead of global variable 3
#12 lambda function
Anonymous functions are suitable for situations where a function similar to a function is temporarily needed but you don't want to define a function,
You can omit the function definition process and consider the function naming, so as to make the code more concise and readable.
myMax = lambda x,y : x if x>y else y #Anonymous function for larger value print(myMax(1,2))
Chapter 9: Python standard library
19. turtle Library
Import turtle Library
from turtle import * Import all, no more points setup( ) Open directly
#Brush
setup( ) Open directly fd(100) Go forward 100, (abbreviation) backward(200) back off seth(180 ) Abbreviation of rotation angle ,Absolute angle setheading circle(100) Draw a circle, counterclockwise circle(100,90) 90 radian undo( ) revoke right( ) Forward right, counterclockwise left( ) Forward left, clockwise goto( ) Moving to absolute coordinates will leave a moving track speed( 1) Set brush speed, 1-10,Greater than 10, instant completion dot(r,color ) Draw a circle with the brush as the center home( ) Brush to the origin, facing east
#Brush state function
direct fd(10) No setup( ) Open penup( )Pick up the brush, the brush can move, but there is no handwriting pendown( ) Put down the brush pensize( ) Brush thickness pencolor( ) stroke color dot( ) Point a point color( )Brush color, fill color clear( ) empty begin_fill( ) Before filling end_fill( ) After filling filling( ) stay begin_fill After that Ture,end_fill front reset( )Empty, reset properties write(' character string',font=('arial',20,'normal') bgcolor( ) Canvas background color hideturtle( ) Hide brush shapes showturtle( ) Display shape isvisible( ) Visible
example:
20. random library
Mason rotation algorithm is not a real random number. It is calculated by the algorithm
seed( ) Initializes the random number seed. The default is the current system time. It does not have to be set It is a seed that can generate a pile of random numbers in the same order random( ) generate[0.0 , 1.0) Random decimal between randint( a,b) generate[a, b]The integer between the left and right are closed intervals getrandbitts(k )Generate memory k Random integer within 0b111 7 Max in memory 3 randrange(a,b[,c])generate[a,b) step c Random integer uniform(a, b )generate[a,b]Random decimal between choice( s) Returns a random element from a sequence shuffle(s) Scramble the sequence and return sample( p,k) from p Random selection in type k Elements returned as a list
choice( ls) randint(a,b) is widely used
Example: # guessing games
from random import* seed(0) x = randint(0,100) while 1: try: s=eval(input('enter a number:')) if s==x: print('bingo!') break elif s>x: print("Big") else: print('Small') except: print('************')
21,time
Time processing, time formatting, timing
from time import * time( ) Returns the timestamp, floating-point number, in seconds, and the number of seconds elapsed from the starting point to the present localtime(time stamp )Return time, structure form, default to current time asctime(localtime()) Standardized output time structure ctime(time stamp )Returns the normalized time string. The default is the current time gmtime( ) Almost and localtime equally mktime(gmtime()) Returns the number of seconds time( ) mktime(gmtime( )) Return timestamp process_time( ) cpu Running time, y-x Calculable program running time sleep(3) cpu Sleep, not counting time time( ) Subtraction can count sleep()Time perf_counter( )Program timing can be performed
# Formatted output of time:
strftime('%a %b %d %H %: M :%S %Y',gmtime()) Time structure required
Y-year,
m-month (01-12), B-month (January), B-month abbreviation
d-day date (01-31)
A-week, a-week abbreviation
H-hour (24), I-hour (12)
M-minutes (00-59)
S-seconds (00-59)
p - morning and afternoon (AM,PM)
It's actually a placeholder to format the output
strptime(x) go back and find the timestamp
Chapter 10: third party Library
22. jieba participle
import jieba jieba.lcut('character string') jieba.lcut('character string',cut_all=True) jieba.lcut_fot_search("character string") jieba.add_word("Word package") Add word pack
23. worldcloud word cloud
from worldcloud import WorldCloud txt="text" words = jieba.lcut(txt) #jieba word segmentation of txt string worldcloud = WorldCloud(font_path= 'Font path', width = ,height='',mask= 'Word cloud shape' font_step= Font size step interval max_font_size= Maximum font size max_words = Maximum number of times, 200 by default stopwords = Excluded list background_color = Picture background color_) #Beautification work worldcloud.generate(text) worldcloud.to_file(filename) #Which file to save as
24. Overview of Python third-party libraries
Please ignore Chinese automatically. Chinese is just for memory
1. Web crawler
import requests
requests.get()
2. Data analysis
numpy number Number (ndim dimension, shape array shape, number of size elements, itemsize memory size)
scipy
pandas
redis-py data storage
PyMongo data storage Monte mountain energy storage
seaborn marine data
3. Text processing direction
pdfminer pdf Text
openpyx1
beautifulsoup4 Beautify text, parse and process HTML and XML
SnowNLP Natural language processing Show show text
xpinyin Pinyin Chinese character to Pinyin
NLTK natural language processing
4. Data visualization
matplotlib image processing
TVTK three-dimensional
mayavi After visualization, it's may
vispy
5. User graphical interface
PyQt5 Image interface Pq5 generation 5 image
wxPython Wechat interface
PyGTK gif picture
6. Machine learning
lscikit - learn
TensorFlow flow thinking surge
Theano
mxnet Neural network node
keras Kress intelligence
PyTorch torch
7. Web development
Django Zhang gou
Pyramid ramid Remi website
Flask flash -- Web site
pylons Long long website
8. Games
pygame
2Panda3D 2D, 3D games
3cocos2d
9. More
PIL image processing
SymPy
WeRoBot WeChat official account
MyQR QR code
loso natural language processing
Luminoth machine vision
TimeSide network audio processing framework
PyOCR image recognition
Like third-party libraries, standard libraries need to be import ed when used