Concise python review (there are some changes on the basis of the original, which are continuously updated)

preface

This paper aims at< Python Fundamentals of language programming (2nd Edition) - song tianlixin, Huang Tianyu. This book summarizes the simple knowledge.

This paper summarizes some common test sites at the end of Huanong python, which is not helpful to the students of Information College and is suitable for the students of other colleges.

I just want to share. I don't mean to show off. I'm sorry if I make you unhappy.

This article may be helpful for programming, but we still need to brush more questions and see more definitions for theoretical knowledge.

Due to my limited energy and ability, please correct the shortcomings of the article.

In addition, you can write your needs, omissions or questions in the comment area, and you will supplement them in time later to answer your questions.

Codeword is not easy. If you feel this article is helpful, you will be very grateful!

Note: the nightingale in the cage is the first-hand author, and I will modify it on its basis

Course supporting experimental questions Click jump

Review points

-Indent, comment, name, variable, reserved word

-Data type, string, integer, floating point number, list, dictionary

-Assignment statement, branch statement, function

-input(), print(), eval(), print(), and their formatting

Combined data type

Sequence types: general operators and functions

Operatordescribe
x in sReturns True if x is an element of s, False otherwise
x not in sReturns True if x is not an element of s, False otherwise
s + tConnect s and t
s * n or n * sCopy sequence s n times
s[i]Index, returns the I + 1st element of the sequence
s[i : j]Slice, excluding the j-th element
s[i : j : k]Step slice, k represents the step size, not written, the default is 1
len(s)Length of sequence s
min(s)Minimum element of sequence s
max(s)Maximum element of sequence s
sum(s)Summation of sequence s (list contains only numbers)
s.index(x)Index of the first occurrence of x in sequence s from left to right
s.rindex(x)The index of the first occurrence of x in sequence s from right to left
s.count(x)Total number of occurrences of x in sequence s

Note: the sequence type is an iteratable object, and you can directly use the for loop operation.

a=[1,2,3,4,5]
for i in a:
    print(i,end='**')  #end is an optional parameter. If it is not written, the default is line feed '\ n'
#Get 1 * * 2 * * 3 * * 4 * * 5**
1234

Collection type

Similar to the mathematical concept of set, the elements are single, and the set does not have the property of automatic ascending arrangement. It may happen that when there are few elements, you can use the sorted() function to sort!
(sets are deterministic, heterogeneous and disordered. Don't confuse them)

Commonly used to: remove the same elements from the list

list1=[5,1,3,7,9,9,2]
list1=list(set(list1))
print(list1)  #Get [1, 2, 3, 5, 7, 9]
# Look, this is ascending automatically, but it's just a coincidence.
print(set([1,3,8,-2,99,98,77,1,5,3,77,12]))  # Get {1, 98, 3, 99, 5, 8, 12, 77, - 2}
#  If you look at this, you won't automatically give you ascending order. You must note that sets don't have the property of automatic ascending order
123456

mapping type

Need to understand:

  1. How to add or delete key value pairs

  2. How to get the tuple corresponding to the key, value and key value in the dictionary

  3. A key can only correspond to one value

Note: the key is the value to the left of the colon. Value is the value to the right of the colon.

Numerical operation

operator

Arithmetic operator describe
x%yFind the remainder of the quotient. For example, 5% 2 results in 1
x//yFind the integer digit of x divided by Y quotient, referred to as integer division. For example, x//y results in 2
x**yFind the y-power of x. For example, the result of 4 * * (1 / 2) is 2, and the result of 3 * * 2 is 9
Comparison operatordescribe
x==y,x!=yJudge whether x is equal or not. If it meets the conditions, it returns True; otherwise, it returns False
x>y,x<yJudge whether x is greater than or less than y, return True if it meets the conditions, otherwise return False
x<=y,x>=yJudge whether x is greater than or equal to y, and also return Boolean value
Assignment Operators describe
x=yAssign the value of y to x. note: it should be used when y is a complex data type Method of copy()
x+=1Equivalent to x=x+1
x-=1Equivalent to x=x-1
x*=2Equivalent to x=x*2
x/=2Equivalent to x=x/2
Logical operatordescribe
andBoolean operation and
orBoolean or
notBoolean operation "not"

The priority relationship is obtained: or < and < not. The same priority is calculated from left to right by default.

member operator describe
a in bReturns True if a is in b
a not in bIf a is not present, b returns True

String operation

String slicing

Basic slice operation

Format: < string to be processed > [M: n].
M missing indicates to the beginning and N missing indicates to the end.
Note: ① the two indexing methods can be mixed; ② The result of the slice does not contain the value of the N index.

a='0123456789'
print(a[1:3])#Get one or two
print(a[1:-1])#Get one, two, three, four, five, six, eight
print(a[-3:-1])#Get seven or eight
print(a[:3])#Get 012
print(a[4:])#Get four five six seven eight nine
123456

Advanced slicing operations

Format: < string to be processed > [M: n: k].
Slice the string according to step K. When k is not written, it defaults to 1, which is equivalent to [M:N].

a='0123456789'
print(a[1:8:2])#Get one three five seven
#Analysis process: in 1 ~ 7, the index starts from 1 and adds 2 successively, i.e. a[1], a[3], a[5], a[7], which are spliced together to obtain 1357
''' ----------------—Beautiful dividing line—————————————————————————————————————— '''
print(a[::-1])#Get 9876543210
#Get the string in reverse order with fixed format. It can be simply understood as operating the selected string segment from right to left [M:N].
''' ----------------—Beautiful dividing line—————————————————————————————————————— '''
1234567

Operations, related functions and related usage methods

Operatordescribe
x+yConnect two strings
x*nCopy string x n times
x in sReturns a Boolean value. If the string x is within s, it returns True. Otherwise, it returns False
correlation functiondescribe
len(x)Returns the length of a string. For example, len('I love handsome dragons') results in 5
str(x)Converts any type of data to a string. For example, str(123) results in the string "123", and str([1,2]) results in the string "[1,2]"
chr(x)Returns A Unicode encoded single character. For example, chr(65) gets the letter "A"
ord(x)Returns the Unicode encoding corresponding to a single character. For example, ord("a") gets the number 97
correlation method describe
str.lower() ,str.upper()Returns a copy that changes all strings to lowercase or uppercase. Example: 'ABC' The result of upper() is' ABC '
str.isalpha()Returns a Boolean value to determine whether the string str is all letters
str.islower(),str.isnumeruic()Returns a Boolean value to determine whether the string str is all lowercase or numeric. If you can't remember the function name. It is recommended to judge whether each character meets the standard by looping and comparing the size
str.split(sep)The string is divided by sep. when sep is not filled in, it is divided by blank by default. Example: 'A,B,C' The result of split(',') is: [A ',' B ',' C ']
str.strip()Remove the empty characters on the left and right sides of the string, \ n \ T, spaces, etc. Example: '\ Ni love handsome dragons' The result of strip() is: 'I love handsome dragons'
str.replace(old,new)Returns a copy, replacing the old character in the string str with the new character. Example: the detailed explanation is as follows

String formatting (does not take much time)

typeFormat Rules
fFormat as floating point number
dFormat as decimal integer
sFormat as string

Format {} format

termIndexes<:>< fill >< align >< width ><,>< accuracy >< type >
effectWhen the format contains multiple data, the index is used to determine the location of the formatted elementGuide symbolCharacters used to fill extra positions< align left
>Right align
^Center alignment
Represents the total length of output, and the excess part will be filled with padding charactersThousands separator for numbers (not commonly used)The precision of a floating-point number decimal or the maximum output length of a stringCharacter s integer d floating point f
Default valueDo not write, default to format content orderMust writeDo not write. The default is spaceAlign leftDo not write. The default is the length of the output characterDo not write default is do not addDo not write default to original precisionDo not write default to original type
a=1.666
print('{0:-^20.1f}'.format(a))  # Get ------------ 1.7---------
12

0 means index

: is the pilot symbol

-Is a fill character

^Indicates center

20 is the total output length

. 1 means to keep one decimal place

%Format

Refer to the c language formatting method. The book uses the format formatting method,% formatting is not introduced here

a=1.555
print('%10.2f'%a)  # Get 1.55
      1.55

%Indicates the pilot symbol

10 indicates width

. 2 means to keep two decimal places

f means to float

list

Note: the general function has been introduced at the beginning of the article. Remember to climb the building.

functiondescribe
ls[i]=xUpdate the element whose list index is i to x
ls.append(x)Add x at the end of the list
ls.insert(i,x)Add the element x in position i of the list
del ls[i]Delete the element with list index i
ls.remove(x)Deletes the first occurrence of the element x from left to right in the list
ls.copy()Get a copy of the list, and the operation on it will not affect the original data
ls.sort()Sort the list from small to large
ls.reverse()Invert list
mylist=sorted(ls)Sorting the copies of the list from small to large does not affect the original order

Some points to pay attention to

Any data type can be stored in the list, but it is not recommended to forcibly convert other data types to the list, but use ls Method of append()

print(list('I love Aaron'))  # Get ['I', 'love', 'ah', 'Dragon']
ls=[]
ls.append('I love Aaron')
print(ls)  # Get ['I love Aaron']
1234

Sorting and reversing the list actually calls the sort() method and reverse() method. It does not return a value. If you enter it, you will get None.

a=[1,3,2,6]
print(a.sort())  # Get None
a.sort()
print(a)  # Get [1,2,3,6]
# reverse the same
12345

List derivation: (master it if you have the ability)

ls=[i for i in range(11)]  # Get [0,1,2,3,4,5,6,7,8,9,10]
ls=[i for i in range(11) if i%5==0]  # Get [5,10]
ls=[(i , j) for i in range(3) for j in range(11,13)]
# Get [(0, 11), (0, 12), (1, 11), (1, 12), (2, 11), (2, 12)]
1234

Dictionaries

dict1={'Rui long Zhang':'Handsome','Liu Hao':'ugly'}
1

As shown above, the key to the left of the colon and the value corresponding to the key to the right of the colon. For example, Zhang Ruilong corresponds to handsome and Liu Hao corresponds to ugly.

Note: ① the existence of key is single, that is, a key can only appear once in a dictionary.

② The types of keys and values can be any type, but they are usually character type

③ When adding elements to a dictionary, keys and values appear in pairs.

functiondescribe
dict1[key]=valueAdd an element to the dictionary. If the key exists, the original corresponding value will be overwritten
list(dict1.keys())Get a list of all the keys in the dictionary
list(dict1.values())Get a list of all values in the dictionary
list(dict1.items())Get the list of all tuple types, keys and values of the dictionary
dict1.get(key,default)If the key exists, the corresponding value is returned. If it does not exist, it is assigned as default
del dict1[key]Delete this key value pair
key in dict1Returns True if the key is in the dictionary, otherwise False

Some points to pay attention to

As an iteratable object, a dictionary is actually its key value

dict1={'Rui long Zhang':'Handsome','Liu Hao':'ugly'}
for i in dict1:
    print(i)
# Obtained by: Zhang Ruilong, Liu Hao
1234

Count the number of occurrences and output from large to small

It can be said that it is the most classic test question. The following block operation.

① Count the number of occurrences

FA Yi

list1=[1,1,1,2,5,3,3,10,5,6,8,9,9,11]
dict1={}  #Create an empty dictionary
for i in list1:
    dict1[i]=dict1.get(i,0)+1  # dict1.get(i,0) means that if any key is i, the corresponding value will be returned; otherwise, 0 will be returned
print(dict1)
12345

Method II

list1=[1,1,1,2,5,3,3,10,5,6,8,9,9,11]
dict1={}  #Create an empty dictionary
for i in list1:
    if i in dict1:  # If the key in the dictionary is i
        dict1[i]+=1  # Add one to the corresponding value
    else:  # If no key in the dictionary is i
        dict1[i]=1  # Create a key value pair with a value of 1 because this is the first occurrence
print(dict1)
12345678

② lambda expression sorting

mylist=list(dict1.items())
mylist.sort(key=lambda x:(-x[1],x[0]))
# When written as mylist Sort (key = lambda x: (x [1], x [0]) sorts values from small to large
# When written as mylist Sort () is sorted by key from small to large
print(mylist)  # Here, you can perform other operations directly according to your needs, rather than converting to a dictionary
dict1=dict(mylist)  # Convert list to dictionary
print(dict1)
1234567

mylist.sort(key=lambda x:(-x[1],x[0]), why add a minus sign here?
Because the sort function sorts from small to large, when the largest positive number is added with a negative sign, it will become the smallest negative number. You can use this feature to meet our needs

In fact, there is an optional parameter reverse in sort, which defaults to Forse. You can try adding the parameter reverse=True in sort to see the effect.
When you write mylist Sort (key = lambda, X: (x [1], x [0]), reverse = true) this can also achieve the output from large to small according to the number of times.
Because the introduction is very cumbersome, just remember this format. If you have any questions, you can write to me directly.

③ To sum up, code summary

list1=[1,1,1,2,5,3,3,10,5,6,8,9,9,11]
dict1={}  #Create an empty dictionary
for i in list1:
    dict1[i]=dict1.get(i,0)+1  # dict1.get(i,0) means that if any key is i, the corresponding value will be returned; otherwise, 0 will be returned
mylist=list(dict1.items())
mylist.sort(key=lambda x:(-x[1],x[0]))
dict1=dict(mylist)  # Convert list to dictionary
print(dict1)
12345678

Tuple, set

It's not the point, but it needs to be simple.

Tuple: it can be replaced by a list. The operation is similar to the list operation. The only difference is that tuples cannot be modified, that is, elements cannot be added or deleted, but can be updated by slicing and addition.

Set: it is often used to clear the same elements, but it does not have the function of automatic sorting.
(but sets are deterministic, heterogeneous and disordered. Don't confuse them.)

list1=[5,1,3,7,9,9,2]
list1=list(set(list1))
print(list1)  #Get [1, 2, 3, 5, 7, 9]
# Look, this is ascending automatically, but it's just a coincidence.
print(set([1,3,8,-2,99,98,77,1,5,3,77,12]))  # Get {1, 98, 3, 99, 5, 8, 12, 77, - 2}
#  If you look at this, you won't automatically give you ascending order. You must note that sets don't have the property of automatic ascending order
123456

Select structure

Operation process

What is the process of this judgment? Let me briefly.

In fact, the judgment standard is Boolean, that is, False or True. For example, the following program.

if 'Loong' in 'Shuai Shuai long':
    print('good')
#The running result is good
print('Loong' in 'Shuai Shuai long')  # The output is True
1234

During program execution, it will first judge whether the following conditions represent True or False

'dragon 'in' handsome Dragon 'will return True, so execute the following procedure

In python, some other things can also be equivalent to Boolean values

Equivalence is TrueEquivalent to False
Number 1Number 0
Non empty stringEmpty string
Non empty listEmpty list
Non empty tupleEmpty tuple
Non empty dictionary (set)Empty dictionary (set)
None
if 1:
    print('Shuai Shuai long')
#The running result is Shuai long
123

if - elif - else branch

The compiler looks for a qualified branch from top to bottom. After entering this branch, it will not enter other branches.

Multiple judgment conditions are to write if - elif - else branch statements, add conditions after if and elif, and no conditions after else.

If you write multiple if instead of multiple branches, errors sometimes occur, as follows:

a=1
if a==1:
    print('a Yes 1')
    a+=1
if a==2:
    print('a It's 2')
# The running result is that a is 1 a nd a is 2

a=1
if a==1:
    print('a Yes 1')
    a+=1
elif a==2:
    print('a It's 2')
# The running result is that a is 1
123456789101112131415

You can think about the problem

Logical operator

a and bWhen both a and b are true, it returns true. If any one is false, it returns false
a or bWhen either a or b is true, it returns true. All for return false
not aReturns the Boolean value opposite to a, or false if a is true

Cyclic structure

continue and break

Continue: terminate the cycle of this layer and continue the cycle of the next layer

break: terminate the loop and exit directly

for i in range(3):
    if i==1:
        continue
    print(i)
# The result is 0 2
###########################
for i in range(3):
    if i==1:
        break
    print(i)
# The result is 0
1234567891011

for loop: often used with a known number of loops

①for i in range(x):

The for loop is actually a simplified form of the while loop, and while can do what the for loop can do.

Range is an iterator that can get iteratable objects. You can output this sentence. See print (list (range (10)))

for i in range(10):# Cycle 10 times    
    print(i)

mylist=[0,1,2,3,4]
for i in range(len(mylist)):
    print(mylist[i])
123456

②for i in x:

mystr='I love handsome dragons'
for i in mystr:
    print(i)
123

while loop: often used to satisfy a condition

The form is while + conditional judgment statement. When the condition returns True, the loop continues, otherwise the loop ends. It is similar to the judgment process of if statement.

while 1: and while True: can represent an endless loop. You need to use break to jump out of the loop

x=0
while x<=5:
	print(x)
    x+=1
#The result is 0 1 2 3 4 5
12345

while - else statement (just understand it)

When the while statement is not interrupted after execution, it will enter the else statement.

If the while statement is interrupted halfway, the else statement will not be entered.

x=0
while x<=5:
	print(x)
    x+=1
else:
    print('get into else la')
# The output result is 0 1 2 3 4 5. Enter else
###########################
x=0
while x<=5:
	if x==1:
        print(i)
        break
	print(x)
    x+=1
else:
    print('get into else la')
# The output is 0 1
123456789101112131415161718

function

Function is to put the code together, improve the readability of the code and make the code reusable. In fact, it is very simple. Don't be afraid of difficulties.

Functions are generally defined before calling, and are usually placed on the top of the program

return and print

Functions often return the result through return. When the return statement of the function is executed, other parts of the function will not be executed.

However, the function may not have a return statement and can directly execute the output statement. However, if you want to output the value of return, you need to use print, which may be a little confused. Look at the code.

def test():
    return 'I love Aaron'
print(test())  #I love Aaron
test()  #Nothing will be output
###########################
def test():
    print('I love Aaron')
print(test())  #I love Aaron and None #Because function does not pass value to print outside function, it is None
test()  #I love Aaron
123456789

Parameters of function

Simple data type as parameter

def test(x):
    x='I love handsome dragons'
    return x
a='rich woman'
a=test(a)
print(a)  # I love handsome dragon
123456

Complex data types as parameters

It should be noted here that when complex data types are used as parameters, they are passed by address (that is, the address of C/C + +, it doesn't matter if you haven't heard of it). The operation of complex data types in functions will directly affect the original data. You should use ls.copy() method (see below for details)

def test(x):
    x.append('handsome guy')
    return x
a=['rich woman']
a=test(a)
print(a)  # Output as ['rich woman', 'handsome man']
###########################    It can also be like the following
def test(x):
    x.append('handsome guy')
a=['rich woman']
test(a)
print(a)  # Output as ['rich woman', 'handsome man']
123456789101112

Optional default parameters

Parameters are divided into shape participating arguments. Formal parameters define that the function is a parameter in parentheses, and arguments are the parameters of the calling function.

However, sometimes the actual parameter is of indefinite length, because the corresponding formal parameter has a default value when defining the function. If you omit the parameter when calling the function, the parameter will be the default value during execution, which is the legendary default parameter.

In fact, there is an end parameter in print(). When you don't write it, it defaults to '\ n', that is, a new line will be automatically output after output.

def test(x='handsome guy',y='rich woman'):
    for i in [x,y]:
        print(i,end='---')
test()  # The result is a handsome man --- rich woman --- because if you don't write, he has a default value
test('Handsome')  # The result is handsome --- rich woman---
test('Handsome','to one's heart's content')  # The result is handsome --- Meimei---
test(y='Handsome',x='to one's heart's content')  # The result is Meimei --- Shuai --- and the corresponding parameters can be specified
1234567

Note: the default parameters should be placed on the rightmost side. When calling a function, the parameters are called from left to right.

global statement (learn about it)

You can modify the global variable directly by introducing it into the function.

Global variable: a variable defined in the main program, which can be used in one function or other functions

Local variable: it can only be used in part of the code. For example, i of for i in range(3) is a local variable

def test():
    global a
    a='rich woman'  #Change a to 'rich woman', where a is actually a of the main function   
a='I love'  # a here is the global variable
test()
print(a)  # Output as rich woman
###########################
def test():
    a='rich woman'
a='I love'
test()
print(a)  # Output for my love
123456789101112

Recursion (learn about it)

Recursion is actually the process of calling functions repeatedly. Recursion needs to set the conditions for ending recursion. There is a default maximum recursion depth (you can reset it). If you do not set it, an error will be reported if the maximum depth is exceeded. The function of recursion can be achieved by using loops.

Here is a recursive factorial

def jiecheng(n):
    if n==1:
        return 1
    else:
        return n*jiecheng(n-1)
print(jiecheng(5))  # The result is 120
123456

When you call this function, you will enter this function. First judge whether the value of n is 1. If it is 1, it will return 1,

If not, return n*jiecheng(n-1), that is, continue to call the function.

In this debugging, n is 5, that is, the result is 5jiecheng(4), and jiecheng(4) represents 4jiecheng(3),

That is, the returned result changes from 5jiecheng(4) to 54*jiecheng(3). Similarly, call down successively until the recursion ends, that is, n==1,

The final result is 54321

txt file reading and writing

We didn't test the programming questions for file operation. We'd better find out the scope of the examination (although generally, the teacher will say that we will test everything we learn)

In fact, it's not difficult here. It only involves the reading and writing of files. Remember to use the close() method to release the use right of files (it's nothing to forget).

Open modedescribe
rOpen as read-only (common)
wOverwrite write. If the file does not exist, it will be created. If it exists, it will be overwritten directly (common)
aAppend write. If the file does not exist, it will be created. If it exists, append write at the end of the document
Methods of reading filesdescribe
f.read()Returns a string containing the entire contents of the file
f.readlines()Returns a list with each element in each row (common)
Method of writing filedescribe
f.write(x)Writing the string x to \ n is a line break in the file (common)

Note: only strings can be written

Written demonstration

f=open('data.txt','w')  # Don't forget to write the file suffix
# If the read data is different from the seen data, write f=open('data.txt','w',encoding='utf-8')
data=['Spring sleep without dawn,','Mosquitoes bite everywhere.','Big bear at night,','Look where you're going.']
for i in data:
    f.write(i+'\n')  #Write it all on one line without adding \ n
f.close()
123456

Reading demonstration

For ease of reading, I directly use the code above to create a file named data Txt file

f=open('data.txt','r')  # Don't forget to write the file suffix
# If the read data is different from the seen data, write f=open('data.txt','r',encoding='utf-8')
data=f.readlines()
data=[i.strip() for i in data]  #Use list derivation to update the contents of data in order to remove line breaks
for i in data:
    print(i)
f.close()
# f.read() is not used because it returns a bunch of strings, which is inconvenient to operate
12345678

Note: file reading and writing is mainly to analyze the text structure. Remember to put \ n and \ t in the written string, otherwise it may not achieve your expected effect.

Some functions

Later, you can add it according to your needs. You can privately poke me or leave a message in the comment area.

. copy() shallow copy (you can't understand it)

def test(x):
    y=x
    y+='I love handsome dragons'
a='rich woman'
test(a)
print(a)  # a is still 'rich woman'
123456

If you change a to a complex data type (list, Dictionary...), the result is different.

def test(x):
    y=x
    y+=['I love handsome dragons']
a=['rich woman']
test(a)
print(a)  # a becomes ['rich woman', 'I love handsome Dragon']
123456

Why?

The reason is that in order to save memory, when a simple data type is passed, only the value is passed. However, complex data types take up a lot of space and pass addresses, which saves the use of memory, but the operation of complex data types will directly change the original data content.

The solution of the problem needs to be used copy() function.

It will copy the data of complex data types to the corresponding variables, so as not to change the original data.

def test(x):
    x=x.copy()
    y=x
    y+=['I love handsome dragons']
a=['rich woman']
test(a)
print(a)  # a is still ['rich woman']
1234567

replace method of string

str.replace(old,new[,count]) returns a copy and replaces the old string with a new string. Count indicates the previous times of replacement. If count is not written, it defaults to all replacement.

Universal method: mystr = mystr Replace (old, new, 1) students who are interested in the following content can have a look. If they are not interested, they can skip

mystr='112'
mystr.replace('1','2')
print(mysrt)  # The result is still 112
123

Why did it fail? In fact, it's just that our use method is wrong, because replace returns a copy of the original string,

The concept of replica has been mentioned above, that is, it will not affect the original data, so write mystr directly Replace does not modify the original string

The modified code is as follows:

mystr='112'
mystr=mystr.replace('1','2')
print(mysrt)  # The result is 222
123

Title Requirements: replace letters in the string with spaces

a='df23A?45cde0@a'  # Do you feel familiar with this test data?? No, I didn't say ha.
for i in a:
    if not ('a'<=i<='z' or 'A'<=i<='Z'):
        a=a.replace(i,' ')
print(a)  # The result is DF a CDE a
12345

Will the data be dirty by directly using replace? Yes or no, let's look at the code. (it is strongly recommended that you don't read it, just remember the universal formula)

# Replace 2 with 1
a='21122'
for i in a:  # Because the string is a simple data type, it is actually equivalent to for i in '21122':
    print(i)
    if i=='2':
        print(a)
        a=a.replace('2','1')  #Because I didn't write count, he will replace all 2
# i sequentially outputs 2 1 2 2
# a outputs 21122 11111 11111 in sequence
# Because the program has determined what i represents in turn during the cycle, updating a will not affect the program
12345678910

isinstance() determines the data format

Type is not convenient to judge what type a variable is, so there is the isinstance() function, which will return a Boolean value.

a=1
print(isinstance(a,int))  # The output is True
12

Note: type(x) is xxx can also be used

a=1
print(type(a) is int)  #Or write it as type(a)==int
12

Python standard library

Introduction mode

import math

Introducing the math library, you can call the functions of the math library

import math
print(math.pow(2,3))  # Get 8.0
12

from math import pow

pow function is introduced from the math library, and no other functions are introduced

from math import pow
print(pow(2,3))  # Get 8.0. Note that math is missing
#However, using other functions will report errors
print(abs(-3))  # Will report an error
1234

import random as ra

Sometimes the name of a function or library is too long. We can rename it
The pow function is introduced from the math library and renamed p

import random as ra
print(ra.randint(10,100))  # Generates random integers from 10 to 100
12

A similar expression is from random import random as random
That is, the randint function is introduced and renamed to RAND

from math import *

Import all functions from Math Library

import math
print(pow(2,3))  # Get 8.0. Note that math is missing
print(abs(-3))  # Get 3
123

math library

First, we should introduce the mathematical library at the beginning of the program. Usage: import math

Common functionsdescribe
abs(x)Get the absolute value of x
pow(x,y)Get the y power of x and return the floating point type
sqrt(x)Square x, or directly x**(1/2)
pi,eThe exact values π, e are obtained

random library

Common functionsdescribe
seed(x)When x is determined, the order of generating random numbers has actually been determined
randint(a,b)Generate random integers between [a,b] (here are two closed intervals!)
choice(seq)Randomly select an element from the sequence type seq
shuffle(seq)Random scrambling of sequence type seq
random()Generate random decimals between [0.0,1.0]
uniform(a,b)Generate random decimals between [a,b] (here are two closed intervals!)

from random import *
seed(10)  #When the seed is certain, the order of generating random numbers is certain!
a=int(input('n:'))
mylist=[]
for i in range(a):
    mylist.append(randint(100,200))
mylist.sort()
for i in mylist:
    print(i)
123456789

About seed, if you are interested, you can go to Baidu to learn more about what seed is in the programming language.
It can be simply understood as: everyone looks different. For example, I may be a little beautiful, but someone named Liu Hao may not be as attractive as me, that is, different people have different facial values, but as long as you choose this person, its facial value is certain.
In random numbers, when seed is determined, the order of random numbers will be determined. Just like when you select a person, his face value has been determined.
Strictly speaking, the random numbers of the computer are generated by pseudo-random numbers (i.e. not random in the strict sense), which are generated by a small M polynomial sequence. Each small sequence has an initial value, that is, a random seed: a small M polynomial sequence. When the initial value is determined, the generated sequence is determined!

jieba Library (no emphasis)

Common functionsdescribe
jieba.lcut(s)Break the string into words and return a list
jieba.lcut(s , cut_all=True)Full mode, returns all words that may be composed of words in the string
jieba.add(s)Add word s to Thesaurus

time library

Common functionsdescribe
sleep(x)The program pauses for x seconds, which is often used in a loop

Some programming skills

IDE selection

A good IDE is half the success. Most downloaded ides have the functions of automatic code completion, error warning and automatic association of corresponding functions and variables, which are very convenient.

If you are still using python's own IDE, you might as well enter 'pr' and click the Tab key on the keyboard. You may have a new discovery.

Recommendation 1: use spyder compiler.

Reason 1: it is easy to download. You can directly search Anaconda on Baidu and download it on the official website.

Reason 2: you don't need to configure your own compiler

Reason 3: many third-party libraries come with Anaconda and do not need additional installation

Recommendation 2: use the pycharm compiler.

Reason: it looks good

Note: if it's just for the exam, you can go to the official website to download the community version. This is enough. If you want to experience the professional edition, why go to the official website and register with the student email

Determine how many lowercase letters are in a string

Sometimes I can't remember the string. What about so many judgment methods? It doesn't matter. In fact, it can be compared directly.

a='aAfSSaDhQoTn'
count=0
for i in a:
    if 'a'<=i<='z':  # Because ASCII code is compared during comparison (lower case letters are larger than upper case letters, you can enter ord('a ') to view)
        count+=1
print(count)  # The result is 6
123456

Judge whether a number is a prime number

def sushu(n):
    for i in range(2,n):  # This is a brainless way of writing. You can also write for i in range(2,int(n**(1/2))+1):
        if n%i==0:
            return False
	return True
a=int(input('Enter a number:'))
print(sushu(a))
1234567

Small application of flag

Sometimes, the purpose of condition judgment can be achieved by setting flag.

Problem Description: judge whether there are numbers in a string

flag=False
mystr='fahu57486sge'
for i in mystr:
    if '0'<=i<='9':
        flag=True
if flag:
    print('have')
else:
    print('No,')
123456789

You can also set multiple flag s to judge the password strength.

Two sets of programming test questions

click here Download. The contents of the compressed package include:
2019 winter python final exam (non Information Institute) -- > three programming questions and one program to fill in the blank
2020 spring python final exam (non Information Institute) -- > five programming questions, with additional reference code

epilogue

I wish you all good grades at the end of the term ✔

Keywords: Python Back-end

Added by merlinti on Tue, 21 Dec 2021 12:36:24 +0200