I always wanted to learn python, so I took teacher Gao Qi's 400 episode course for several months. As a result, I saw less than 30 lessons in a few months. This time, I was isolated in Xi'an. It was boring to stay in the dormitory, so I decided to calm down and finish learning python. OK. Then sort out the notes of these days and just review them.
This note is based on the explanation of Mr. Gao Qi's course. You can go to see Mr. Gao Qi's python course. It's very good. So let's start.
import turtle t = turtle.Pen() for x in range(360): t.forward(x) t.left(59)
- The blank space at the beginning of a logical line (spaces and tabs) is used to feel the indentation level of the logical line, so as to determine the grouping of statements
- Statement starts with the first column of the new row
- Uniform indentation style:
- Use a single tab or four spaces for each indent level
- python uses indentation instead of {} to represent program blocks
notes
Line comment: add a # sign before each line comment. When the interpreter sees #, it ignores the content segment after this line #. Note: use three consecutive single quotation marks (''). When the interpreter sees' '', it will scan to the next '', and then ignore the content between them.
#1. Line notes ''' 2. paragraph notes Buddhism '''
Line linker
There is no limit to the length of a one line program, but in order to be more readable, a program with a long line is usually divided into multiple lines. At this time, we can use the \ line connector and put it at the end of the line. The Python interpreter still interprets them as the same line.
a = [10,20,30,40,\ 50,60,70,\ 80,90,100] # Output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
a = 'abcdefghijklmnopqrstuvwxyz' b = 'abcdefg\ hijklmn\ opqrst\ uvwxyz' c = 'abcdefg\ hijklmn\ opqrst\ uvwxyz' # Output: # a: abcdefghijklmnopqrstuvwxyz # b: abcdefghijklmnopqrstuvwxyz # c: abcdefg hijklmn opqrst uvwxyz
object
The essence of an object is a memory block that has specific values and supports specific types of related operations
- Identification is used to uniquely identify an object, usually corresponding to the address of the object in computer memory. Use the built-in function id(obj) to return the identification of the object obj.
- Type is used to represent the type of data stored by the object. Type can limit the value range and executable operations of an object. You can use type(obj) to get the type of the object.
print(id(3)) #2573173418352 print(type(3)) #<class 'int'> a=3 print(id(b)) #2573173418352 print(type(b)) #<class 'int'> b="I love you!" print(id("I love you!")) #2166580334832 print(id(b)) #2166580334832 print(type("I love you!"))#<class 'str'> print(type(b)) #<class 'str'>
quote
In Python, variables also become: references to objects. Because the variable stores the address of the object. The variable references "object" by address. The variable is located in: stack memory (details such as pressing and exiting the stack will be described later). The object is located in: heap memory.
identifier
- Case sensitive. For example, SXT and SXT are different
- The first character must be a letter or underscore. The following characters are: letters, numbers, underscores
- Keywords cannot be used. For example: if, or, while, etc.
- Names that begin and end with double underscores usually have special meanings. Try to avoid this writing. For example:__ init__ Is the constructor of the class
Delete variables and garbage collection mechanism
a=123 del a
assignment
Chain assignment: chain assignment is used to assign the same object to multiple variables x=y=123, which is equivalent to x=123; y=123
Series unpacking assignment: give variables a,b,c=4,5,6 corresponding to the same number, which is equivalent to: a=4;b=5;c=6
a,b,c=1,2,3 print(a,b,c) #1 2 3 a,b,c=c,b,a print(a,b,c) #3 2 1
constant
Python does not support constants, that is, there are no syntax rules that restrict changing the value of a constant. We can only agree on the naming rules of constants and do not modify the value of constants in the logic of the program.
Most basic built-in data type
- Integer: 2345,10,50
- Floating point: decimal, 3.14 or scientific counting 314e-2
- Boolean: indicates True or False, only including: True and False
- String type: a sequence of characters. "abc", "sxt", "shangxuetang", "Baizhan programmer"
operator
Add 3 + 2 = 5
Subtraction 30-5 = 25
Multiplication 3 * 6 = 18
/Floating point division 8 / 2 = 4.0
//Integer division 7 / / 2 = 3
%Module (remainder) 7% 4 = 3
**Power 2 * * 3 = 8
print(7/3) #2.3333333333333335 print(7//3) #2
Type conversion using int()
print(int(123)) #123 print(int(123.453453453)) #123 print(int("435353")) #435353 print(int(True)) #1 print(int(False)) #0 # ((error) print(int("2342sfsdgdg")) #If this cannot be converted, an error will be reported
Representation of time
Computer time is expressed in milliseconds (1 / 1000 second) starting from "00:00:00, January 1, 1970". We also call this time in 1970 "unix time point"
import time print(time.time()) #From 1970 to today, there are 1635488450.2000031 seconds totalSecond=int(time.time())#From 1970 to today, there are 1635488510 seconds totalMinute=totalSecond//60 # from 1970 to today, there are 27258143 minutes totalHour=totalMinute//60 # from 1970 to today, there are 454302 hours totalDay=totalHour//24 # from 1970 to today, there are 18929 days totalYear=totalDay//365 # 51 years from 1970 to today
Boolean value
Boolean: True and False are defined as keywords, but their qualities are still 1 and 0, and can even be added to numbers
Comparison operator
All comparison operators return 1 for True and 0 for False. This is equivalent to the special variables True and False, respectively
The following assumes that variable a is 15 and variable b is 30:
- ==(equal): whether the values of the comparison object are equal (a == b) returns False
- != (not equal): compares whether the values of two objects are not equal (a! = b) returns true
-
>(greater than): Returns whether x is greater than y (a > b) returns False
- < (less than): Returns whether x is less than y (a < b) returns true
-
=(greater than or equal to): Returns whether x is greater than or equal to y. (a > = b) returns False
- < = (less than or equal to): Returns whether x is less than or equal to y. (a < = b) returns True
Logical operator
- Or logical or (x or y): if x is true, y will not be calculated and will be returned directly; if x is false, y will be returned
- And logical and (x and y): if x is true, the value of Y is returned; if x is false, y is not calculated and false is returned directly
- Not logical non (not x): X is true and returns false
print(3==4) #False print(3<4) #True print(5!=5) #False print(3 and True) #True print(3 and False) #False print(3>5 or True) #True print(not 3) #False
Same operator
- The same operator is used to compare the storage units of two objects. The actual comparison is the address of the object.
- Operator description
- Is: is determines whether two identifiers refer to the same object
- Is not: is not determines whether two identifiers refer to different objects
- Is is different from = =
- Is is used to determine whether two variable reference objects are the same, that is, the address of the comparison object
- ==It is used to judge whether the values of the reference variable and the reference object are equal. The eq() method of the object is called by default
Integer cache problem
Python only caches small integer objects (range [- 5, 256]) instead of all integer objects. It should be noted that this is only executed on the command line, but the result is different when it is executed in pychar or saved as a file. This is because the interpreter has made some optimization (range [- 5, any positive integer]).
summary
- is compares whether the id values of two objects are equal and point to the same memory address
- ==The comparison is whether the contents and values of two objects are equal
- The small integer object [- 5256] is cached for reuse within the global interpreter
- The is operator is more efficient than = = and should be used when comparing variables with None
print(id(3)) #140715204334688 a=3 # 3 has an address, a points to the address where 3 is stored, and so does b b=3 print(id(a)) #140715204334688 print(id(b)) #140715204334688 print(a == b) #True compares whether two values are equal print(a is b) #True compares whether two addresses are equal print(a is 3) #True print(a is 4) #False
character string
a='sxt' #sxt b="sxt" #sxt c="I'm a teacher" #I'm a teacher #((error) d='I'm a teacher' # 'pair with' in the sentence, so it's best to use double quotation marks at this time e='my_name is "YanShen"' # my_name is "YanShen" #((error) f="my_name is "YanShen"" # '' matches' 'in the sentence, so it's best to use single quotes at this time # Three quotation marks can write many lines, and avoid the matching problem of '' and 'in sentences resume='''name="Yan Shen" company = "Bath" age = 13 lover = "TOM" ''' g='' print(a,b,'\n',c,'\n',e,'\n',resume,'\n',g) print(len(g),len(resume)) #0 50
ord() & chr()
- ord() can convert characters into corresponding Unicode codes
- chr() can convert decimal numbers to corresponding characters
print(ord('A')) #65 print(ord('word')) #39640 print(chr(66)) #'B' print(ord('deep')) #28103
Escape character
Continuation character (at the end of a line)
\Backslash symbol
'single quote
Double quotes
\b backspace
\n line feed
\t horizontal tab
\r enter
a = 'I\nlove\nU' ''' I love U ''' print(a) print('aaabb\ cccddd') # aaabbcccddd
String splicing
You can use + to splice multiple strings.
For example: 'AA' + 'BB' = > 'AABB'
- Splice if both sides of + are strings
- If both sides of + are numbers, the addition operation
- If the types of + are different, an exception is thrown
a='aa''bb' print(a) #aabb a='aa' b='bb' print(a+b) #aabb
You can splice multiple literal strings directly together. For example: 'AA' 'BB' = > 'AABB'
String copy
a='abc' print(a*10) # abcabcabcabcabcabcabcabcabcabc
str() implements numeric transformation string
str() can help us convert other data types to strings
str(5.20) ==> '5.20'
str(3.14e2)==>'314.0'
str(True) ==> 'True'
When we call the print() function, the interpreter automatically calls str() to convert non string objects into strings
a=123 b=345 print(a+b) #468 a=str(a) b=str(b) print(a+b) #123456
Extract characters using []
The essence of a string is a character sequence. We can extract a single character at this position by adding [] after the string and specifying the offset in []
- The leftmost first character, offset 0, and the second offset 1, until len(str)-1
- The rightmost first character, offset - 1, and the penultimate offset - 2 until - len(str)
a="abcdefg" a_len=len(a) print(a[1]) # Second character b print(a[1+2]) # b right two characters d print(a[a_len-1]) # Last character g print(a[a_len-1-2]) # g left two characters e print(a[-1]) # Last character g print(a[-7]) # The seventh character from the tail, that is, the first character a
replace() implements string replacement
- The string is "immutable". We can get the characters at the specified position of the string through [], but we can't change the string. We tried to change a character in the string and found an error
- The string cannot be changed. However, we do sometimes need to replace some characters. At this point, you can only do this by creating a new string
a="abcdefg" print(a) #abcdefg a points to the space where abcdefg is stored b=a.replace('c','word') print(b) #ab high defg b points to the space of ab high defg a=b print(a) #ab high defg a points to b points to the space
String slicing operation
a="abcdefghijklmn" print(a[1:3]) # bc output between the 2nd and 3rd characters print(a[1:5:2]) # bd output every 1 character between the 2nd and 6th characters print(a[1:500]) # abcdefghijklmn if the number of characters exceeds the range, it is calculated directly according to the length of the string print(a[1:500:2]) # Similarly #---------------------------------------------------- print(a[:]) # abcdefghijklmn output all characters print(a[1:]) # bcdefghijklmn outputs all characters starting from the second print(a[:7]) # abcdefg from the beginning to the 7th character print(a[::2]) # acegikm starts with the first character and outputs one character every other #---------------------------------------------------- print(a[-1:-3]) # No output print(a[-3:-1]) # lm output from penultimate 3 to penultimate 2 print(a[:-1]) # abcdefghijklm output from the beginning to the penultimate character print(a[-1:]) # n output all the next characters from the penultimate one print(a[::-1]) # nmlkjihgfedcba outputs in reverse print(a[::-2]) # nljhfdb starts from the last one and outputs one character every other
split() split string
a="to be or not to be" b=a.split() # b=['to','be','or','not','to','be'] # If no delimiter is specified, white space characters (newline / space / tab) are used by default # You can separate a string into multiple substrings based on the specified separator print(b[1]) b=a.split('be') # Use be as separator print(b[0],b[1]) # b=['to','or not to']
join() merge string
b=['to','be','or','not','to','be'] a='*'.join(b) print(a) # to*be*or*not*to*be a=''.join(b) print(a) # tobeornottobe
String resident mechanism
String resident: a method to save only one copy of the same and immutable string, and different values are stored in the string resident pool. Python supports string persistence mechanism. String persistence mechanism will be enabled for strings that comply with identifier rules (only including underscores (), letters and numbers). However, for pycharm, it seems that the persistence mechanism can be started whether they comply with identifier rules or not
a="abd_33" b="abd_33" c="dd#" d="dd#" print(a is b) # True print(c is d) # True
Member operator
in /not in keyword to judge whether a character (substring) exists in the string.
a="aabbccdd" print("aa" in a) # True print('a' in a) # True print("aabbccdd" in a) # True
Common search methods
len()
startswith()
endswith()
find()
rfind()
count()
isalnum()
a="I'm Yan Shen. Yan Shen loves making videos" print(len(a)) # String length 96 print(a.startswith('I mean deep')) #True starts with the specified string print(a.endswith('Make video')) #True ends with the specified string print(a.find('word')) #2 the position where the specified string first appears print(a.rfind('word'))#5 position of the last occurrence of the specified string print(a.count("Yan Shen")) #2 how many times does the specified string appear print(a.isalnum()) #False all characters are letters or numbers
Remove head and tail information
strip()
print(" haha ".strip()) # Clear leading and trailing whitespace by default haha print("***haha***".strip("*")) # Clear head and tail * symbol haha print("**h*a*h*a**".strip("*")) # Clear the beginning and end * symbols, but the middle * does not remove h*a*h*a print("*****haha*".lstrip("*")) # Remove the * symbol on the left, haha*
toggle case
capitalize()
title()
upper()
lower()
swapcase()
a = "gaoqi love programming, love SXT" print(a.capitalize()) # Generate a new string with the first letter of the word uppercase and the rest lowercase 'Gaoqi love programming, love sxt' print(a.title()) # Generate a new string with each word capitalized 'Gaoqi Love Programming, Love Sxt' print(a.upper()) #A new string is generated, and all characters are converted to uppercase 'GAOQI LOVE PROGRAMMING, LOVESXT' print(a.lower()) #A new string is generated, and all characters are converted to lowercase 'gaoqi love programming, love sxt' print(a.swapcase()) #Generate new, all letters case conversion 'GAOQI LOVE PROGRAMMING, LOVEsxt'
Format layout
center()
ljust()
rjust()
a="SXT" print(a.center(10,"*")) # Align in the middle, a total of 10 characters, and fill the rest with * * * * SXT**** print(a.center(10)) # Align in the middle, a total of 10 characters, and fill the rest with spaces print(a.ljust(10,"*")) # Align left, 10 characters in total, and fill the rest with *
inspect
isalnum()
isalpha()
isdigit()
isupper()
islower()
print("sxt100".isalnum()) #Is it alphanumeric True print("sxt Shang Xuetang".isalpha()) #Detect whether the string is only composed of letters (including Chinese characters) False print("234.3".isdigit()) #Detects whether the string is only composed of numbers. False because there is a decimal point print("23423".isdigit()) # True print("aB".isupper())#Is it a capital letter False print("A".isupper())#True print("\t\n".isspace())#Detect whether the blank character is True print("aa".islower() )#Is lowercase True
Formatting of strings
format()
a = "The name is:{0},Age is:{1}" # {} stands for placeholder, 0,1 stands for 0, 1 print(a.format("Yan Shen",18)) #Output: 'Name: Yan Shen, age: 18' # If you use placeholder {}, you should pay attention to the order of elements b = "The name is:{0},Age is{1}. {0}He's a good guy" print(b.format("Yan Shen",18)) # 'the name is Yan Shen, and the age is 18. Yan Shen is a good guy ' c = "The name is{name},Age is{age}" print(c.format(age=19,name='Yan Shen'))# 'name is Yan Shen, age is 19' # In this mode, there is no need to consider the order of elements
Align and fill
# ^, <, > are centered, left aligned and right aligned respectively, followed by width # : the filled character after the sign can only be one character. If it is not specified, it is filled with spaces by default print("{:*>8}".format("245")) # '*****245' print("I am{0},I like numbers{1:*^8}".format("Yan Shen","666")) # 'I mean, I like numbers * * 666 * * *'
Number formatting
a = "I am{0},What's my deposit{1:.2f}" print(a.format("Yan Shen",3888.234342)) # 'I'm Yan Shen. My deposit is 3888.23' print("{:.2f}".format(-3.12)) # Retain two decimal places -3.12 print("{:+.2f}".format(-3.124)) # Signed, with two decimal places reserved -3.12 print("{:.0f}".format(3.123)) # Without decimal 3 print("{:.0f}".format(3.983)) # 4 print("{:,}".format(1000000000)) # Comma separated number format 1000000000 print("{:.3%}".format(0.4533425)) # Percentage format 45.334% print("{:.2e}".format(10000000000)) # Exponential notation 1.00e+10
Variable string
In Python, strings are immutable objects and cannot be modified in place. If you need to modify the value, you can only create a new string object. However, often we do need to modify the string in place. You can use io Stringio object or array module
import io s = "hello,sxt" sio = io.StringIO(s) print(sio) # <_io.StringIO object at 0x000001FF26533708> print(sio.getvalue()) # hello, sxt sio.seek(7) # Find the 8th character, x sio.write("g") # Change to g print(sio.getvalue()) # hello, sgt
Non wrapping printing
End = "any string". Add anything at the end of the implementation
print("agdf",end='') #agdf end empty characters do not wrap print("sdaffs",end='\n') #sdaffs end newline character print("fsfsdfs",end="%#%#$%#") #fsfsdfs ending%#%#$%#nowrap ''' Output: agdfsdaffs fsfsdfs%#%#$%# '''
Read string from console
We can use input() to read the keyboard input from the console
myname=input("Please enter your first name:") # Please enter your name: * * * Yan Shen*** print(myname) # Yan Shen
list
List creation
list()
range()
# First kind a = [10,20,'YanShen','sxt'] b = [] #Create an empty list # Second # Any iteratable data can be converted into a list using list(). a = list() # Create an empty list object b = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] c = list("YanShen,sxt") # ['Y', 'a', 'n', 'S', 'h', 'e', 'n', ',', 's', 'x', 't'] # range() creates a list of integers ''' range() The syntax format is: range([start,] end [,step]) start Parameter: optional, indicating the starting number. The default is 0 end Parameter: required, indicating the ending number step Parameter: optional; indicates step size; the default value is 1 python3 in range()Returns a range Objects, not lists. We need to pass list()Method to convert it to a list object. ''' list(range(3,15,2)) # [3, 5, 7, 9, 11, 13] list(range(15,3,-1)) # [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4] list(range(3,-10,-1))# [3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9] # Third # Derived generation list a = [x*2 for x in range(5)] #Loop to create multiple elements [0, 2, 4, 6, 8] b = [x*2 for x in range(100) if x%9==0] # Filter elements by if [0, 18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]
Addition and deletion of list elements
When the list adds and deletes elements, the list will automatically manage the memory, which greatly reduces the burden of programmers. However, this feature involves a large number of movement of list elements, which is inefficient. Unless necessary, we usually only add or delete elements at the end of the list, which will greatly improve the operation efficiency of the list.
append()
# Modifying the list object in place is the fastest way to add new elements at the end of the real list. It is recommended. a=[10,20,30,40] a.append(50) print(a)
+Operator operation
a=[10,20,30,40] print(id(a)) # 3089976854920 a=a+[50] print(a) # 10 20 30 40 50 print(id(a)) # 3089550303880 # Through the above test, we found that the address of variable a changed. That is, a new list object is created
extend()
# Adding all elements of the target list to the end of this list is an in place operation and does not create a new list object. a=[10,20,30,40] b=[50,60] a.extend(b) print(a) # [10, 20, 30, 40, 50, 60]
insert()
Using the insert() method, you can insert the specified element into any specified position of the list object. This will move all elements behind the insertion position, which will affect the processing speed. When a large number of elements are involved, try to avoid them. Similar functions that perform this movement include: remove(), pop(), del(). When deleting non tail elements, they will also move the elements behind the operation position.
a=[10,20,30,40] a.insert(1,9) print(a) # [10, 9, 20, 30, 40]
Multiplication extension
a=[10,20,30,40] a=a*3 print(a) # [10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 40]
Deletion of list elements
del()
# Deletes the element at the specified location in the list. a=[10,20,30,40,50] del a[1] print(a) # [10, 30, 40, 50]
pop()
# pop() deletes and returns the element of the specified location. If no location is specified, the last element of the default action list a=[10,20,30,40,50] print(a.pop()) # 50 print(a) # [10, 20, 30, 40] print(a.pop(1)) # 20 print(a) # [10, 30, 40]
remove()
# Delete the first occurrence of the specified element, and throw an exception if the element does not exist. a = [10,20,30,40,50,20,30,20,30] a.remove(20) print(a) # [10, 30, 40, 50, 20, 30, 20, 30]
List element access and counting
Direct access to elements by index
a=[10,20,30,40,50] print(a[2]) # 30
index()
# Gets the index of the first occurrence of the specified element in the list # index() can get the index position of the first occurrence of the specified element. The syntax is: index(value,[start,[end]]). # Where start and end specify the scope of the search. a=[10,20,30,40,50,10,20,10] b = a.index(10) # 0 c = a.index(10,1) # 5 position 10 after the second element d = a.index(10,3,7) # 5 between the 4th element and the 8th element, the position of 10
count()
a=[10,20,30,40,50,10,20,10] # count() returns the number of times the specified element appears in the list print(a.count(10)) # 3
len() returns the length of the list
a=[10,20,30,40,50,10,20,10] # len() returns the length of the list, that is, the number of elements contained in the list. print(len(a)) # 8
Membership judgment
a=[10,20,30,40,50,10,20,10] print(20 in a) # True print(100 not in a) # True print(30 not in a) # False
Slicing operation
''' section slice Operation allows us to quickly extract sub lists or modify them. The standard format is: [Start offset start:End offset end[:step step]] Note: when the step size is omitted, the second colon can be omitted # [:]: extract the entire list # [start:]: from start to end of index # [: end]: know end-1 from the beginning # [start:end]: from start to end-1 # [start:end:step]: extract from start to end-1, and the step is step # Other operations (three quantities are negative): # [10,20,30,40,50,60,70] [- 3:] last three [50,60,70] # -7 -6 -5 -4 -3 -2 -1 # [10,20,30,40,50,60,70] [- 5: - 3] from the fifth to the third from the bottom (including the head but not the tail) [30,40] # [10,20,30,40,50,60,70] [: - 1] steps are negative, from right to left # Reverse extraction [70, 60, 50, 40, 30, 20, 10] '''
Traversal of list
a=[10,20,30,40,50,10,20,10] for x in a: print(x,end=' ') # 10 20 30 40 50 10 20 10
sort list
# First kind a = [20,10,30,40] a.sort() #The default is ascending print(a) # [10, 20, 30, 40] a = [10,20,30,40] a.sort(reverse=True) #Descending order print(a) # [40, 30, 20, 10] import random random.shuffle(a) #Disorder order print(a) # [40, 30, 20, 10] random.shuffle(a) #Disorder order print(a) # [10, 20, 40, 30] every disturbance may be different # The second method is to create a new list # We can also sort through the built-in function sorted(). This method returns a new list without modifying the original list. a = [20,10,30,40] id(a) # 46016008 a = sorted(a) #Default ascending order id(a) # 45907848 a = [20,10,30,40] id(a) # 45840584 b = sorted(a) id(a) # 45840584 id(b) # 46016072 print(a) # [20, 10, 30, 40] print(b) # [10, 20, 30, 40] c = sorted(a,reverse=True) #Descending order # Through the above operations, we can see that the generated list objects b and c are completely new list objects.
reversed() returns the iterator
# reversed() does not make any changes to the original list, but returns an iterator object in reverse order. a = [20,10,30,40] c = reversed(a) print(c) # Is not a list type # <list_reverseiterator object at 0x000002382F9760F0> print(list(c)) # [40, 30, 10, 20]