Review the recent videos and forget them

Chapter I

1. Output function print

#You can output numbers
print(520)
print(58.5)

#Output string
print('hello world')
#Expression with operator
print('3+1')
print("hello")
print(3+1)
#Export data to a file
fp=open('D:/text.txt','a+')
print('hello world',file=fp)
fp.close
a=open('D:/text2.txt','a+')#If the file does not exist, it will be created. If it exists, it will continue to be appended after the file content
print('hahahah',file=a)
a.close()
#No newline output, the output content is in one line
print('hello','world','python')

The output string plus' 'is very basic Double quotation marks are OK

2. Escape character

Definition: backslash plus the first letter of the transfer function you want to achieve

#Escape character
print('hello\nworld')#Newline, n is newline
print('hello\tworld')#And t occupy four squares. If there are some, they are made up of four. They are not filled in. T is a tab
print('hello\rworld')#world overwrites hello. r is return
print('hello\bworld')#Back space
print('The teacher said:''hello everyone')
print('The teacher said:\Hello, everyone\')
print(r'hello \nworld')#The original character, so that the escape character does not work, add R or r before the string. Note that the last character cannot be a backslash, and two can

Chapter I summary

Chapter II

1. Binary and character encoding

2. Identifier and reserved word in python

3. Variables and data types in Python

4. Comments in Python

2. Viewing method of reserved words:

import keyword
print(keyword.kwlist)

3. Definition and use of variables and multiple assignment of variables

name='Maria'
print(name)#The variable consists of three parts: identification id (obj) type type value print print print the value
print('identification',id(name))
print('type',type(name))
print('value',name)
name='Maria'
print(name)
name='Chu Liubing'
print(name)

4. Common data types

​

#Data type integer type floating point number type boolean type string type


#Integer type int
#It can be expressed as a positive number and a negative number 0
n1=90
n2=-39
n3=0
print(n1,type(n1))
print(n2,type(n2))
print(n3,type(n3))
#Integers can be expressed as 2, 8, 10, hexadecimal, and the default is hexadecimal
print('decimal system',118)
print('Binary',0b100010)#Add 0b before binary
print('octal number system',0o12322)#Octal preceded by 0o
print('hexadecimal',0x1EAF)#Hex preceded by 0x


#float type
a=3,14159
print(a,type(a))#No, I don't really want to learn
n1=1.1
n2=2.2
n3=2.1
print(n1+n2)#The computer uses binary storage, so the floating-point number calculation is inaccurate and there will be errors
print(n1+n3)#This is normal. This is the case. Don't tangle
#By importing module decimal
from decimal import Decimal
print(Decimal('1.1')+Decimal('2.2'))


#Boolean type bool
f1=True  #Indicates 1
f2=False#Indicates 2
print(f1,type(f1))
print(f2,type(f2))
#Boolean values can be converted to integer operations
print(f1+1)
print(f2+1)



#String type str
str1='I really want to break up'
print(str1,type(str1))
str2="It's like breaking up"
print(str2,type(str2))
str3="""I miss it
 break up"""
print(str3,type(str3))

​

5. Data type conversion

#Type conversion str() and int()
name='Zhang San'
age=20
print(type(name),type(age))#The data types of name and age are different
print('My name is'+name+'this year,'+str(age)+'year')#type error error in type #The plus sign is a connection symbol. When str is connected with int type, an error is reported. The solution is type conversion
#print('My name is' + name + 'this year,' + age + 'years') this is an error. The int() function is converted into str() type through str() function, so no error is reported

print('---------str()Convert other types to str Type————————')
a=100
b=False
c=12.2
print(type(a),type(b),type(c))
print(str(a),str(b),str(c))
print(type(str(a)),type(str(b)),type(str(c)))

print('----------int()Convert other types to int type-----')
s1='123'#This is a string
f1=89.2
s2='78.99'
ff=True
s3='hello'#Don't do it directly. str must be converted to an integer, not text or decimal
print(type(s1),type(f1),type(s2),type(ff))
print(int(s1),type(int(s1)))#To convert str to int type, the string should be a numeric string
print(int(f1))#Convert float to int type, intercept the integer part and round off the decimal part
# #print(int(f2))#An error is reported when str is converted to in because the string type is a decimal string
print(int(ff))
print('----------float()Convert other types to float type-----')
s1='12.3'
s2='78'#78.0
ff=True
s3='hello'#Can't turn
i=98#98.0

Chapter II knowledge summary

Chapter III

1.python input function (input)

2. Operators in Python

Arithmetic operator

Assignment Operators

Comparison operator

Boolean operator

Bitwise Operators

3. Operator priority

 

1. Input function input

#Basic use of input function

present=input('What gift do you want?')
print=(present)


#Advanced use

#Enter two integers from the keyboard, and then calculate the sum of the two integers
a=int(input('Please enter an addend:'))
#a=int(a)#Store the converted results in a
b=input('Please enter another addend:')
b=int(b)
print(a+b)

print(1+1)

2. Operators in Python

 

Arithmetic operator

#Arithmetic operator


print(1+1)
print(1-1)
print(2*2)
print(1/2)
print(11//2) The # integer division operation takes only the integer part of the result
print(11%2)#Remainder operation
print(2**3)#exponentiation 
print(9//4)
print(-9//-4) The # results are the same as above, both 2
print(9//-4)
print(-9//4) # one positive and one negative are rounded down, and the largest integer smaller than itself is taken
print(9%-4)
print(-9%4)#Formula: remainder = divisor divisor * quotient 9 - (- 4) * (- 3) - 9-4 * (- 3)


Assignment Operators

#Assignment operator, operation order from right to left
a=3+4
print(a)
a=b=c=20 #Chained assignment 
print(a,id(a))
print(b,id(b))
print('----------Support parameter assignment')
a=20
a+=30#Equivalent to a=a+30
print(a)
a-=20#Equivalent to a-20 assigned to a
print(a)
a*=2
print(a)
print('----------Support series unpacking assignment')
a,b,c=10,20,30
print(a,b,c)#The number of left and right variables should be the same as the number of values, otherwise an error will be reported
print('----------Exchange the values of two variables')
a,b=10,20
print('Before exchange',a,b)
#exchange
a,b=b,a
print('After exchange',a,b)

 

Comparison operator

#Comparison operators, <, >, < =, > =,! === Is not the comparison result is true and false

a,b=10,20
print('a>b Are you?',a>b)#The result of the comparison operator is of type bool
print('a>=b Are you?',a>=b)
print('a==b Are you?',a==b)
print('a!=b Are you?',a!=b)#Isn't a equal to b


'''One=Called assignment operator,==It is called a comparison operator
 A variable consists of three parts to identify the type value
==Values are compared
is The comparison is the identification'''
a=10
b=10
print(a==b)#Indicates that value is equal
print(a is b)#Description id is equal to id
#I haven't learned the following
lst1={11,22,33,44}
lst2={11,22,33,44}
print(lst1==lst2)#value
print(lst1 is lst2)
print(id(lst1))
print(id(lst2))


print(a is not b)#Identification id
print(lst1 is not lst2)

Boolean operator

#Boolean operator
a,b=1,2
print('----------------and also')
print(a==1and b==2)
print(a!=1and b==2)
print(a!=1 and b!=2)
print('--------------or perhaps')
print(a==1 or b==2)
print(a!=1 or b==2)
print(a!=1 or b!=2)
print('-------------not yes bool Operand inversion of type')
f=True
f1=False
print(not f1)
print(not f)
print('------------in And not in')
s='hello world'
print('w'in s)
print('k' in s)
print('w' not in s)

Bit operator, related to binary, to be determined, don't learn

Operator precedence

Calculate multiplication and division before addition and subtraction. If there is power operation, calculate the {arithmetic operator first

Bit operation

The result of the comparison operation is true or false

Boolean operation

Assignment operation

(brackets are calculated first)

Chapter III summary

Chapter IV

1. Organizational structure of the procedure

2. Sequential structure

3. Boolean value of object

4. Branch structure

Single branch if structure

Double branch if else structure

Multi branch if elif else structure

Nesting of if statements

Conditional expression

5.pass empty statement

Sequential structure and Boolean value of test object

#Sequential structure
'''How many steps does it take to put the elephant in the refrigerator'''
print('1,Open the refrigerator')
print('2,Put the elephant in the fridge')
print('3,Close the refrigerator door')
print('---------Program end-----------')

#Boolean value of the test object
print('------------The Boolean values of the following objects are false-----')
print(bool(False))#false
print(bool(0))
print(bool(None))
print(bool(''))
print(bool(""))
print(bool([]))#Empty list
print(bool(list()))#Empty list
print(bool(()))#Empty tuple
print(bool(tuple()))#Empty tuple
print(bool({}))#Empty dictionary
print(bool(dict()))#Empty dictionary
print(bool(set()))#Empty set
print('-------------Boolean values for other objects are true----')
print(bool(8))
print(bool(True))
'''..........'''

Branch structure (very important)

Single branch structure and double branch structure

#Single branch structure
money=1000#balance
s=int(input('Please enter withdrawal amount'))#Withdrawal amount
#Judge whether the balance is sufficient
if money >=s:
   money=money-s
   print('Withdrawal succeeded, and the balance is:',money)

#Double branch structure if Else, choose one from two
'''Input an integer from the keyboard and write a program to let the computer judge whether it is odd or even'''
a=int(input('please enter a number'))
if a%2==0:
    print('It's an even number')
else:
    print('Odd number')

Multi branch if elif else structure

'''Multi branch structure, select one to execute
 Enter an integer from the keyboard
90-100 A
80-89 B
70-79 C
60-69 D
0-59 E
 Less than 0 or more than 100 is illegal data (not a valid range of scores)'''
score=int(input('Please enter a grade'))
#judge
if score >=90 and  score<=100:
    print('A')
elif score>=80 and score<90:
    print('B')
elif 70<=score<80:#This is also ok in python
    print('C')
elif score>=60 and score<70:
    print('D')
elif score>=0 and score<60:
    print('E')
else:
    print('error')

Nesting of if statements

#Branch structure, use of nested if
'''member >=200 8 fracture
       >=100 9 fracture
       Others are not discounted
 Non member  >=200 9.5 fracture
       Others are not discounted'''
a=input('Are you a member? y/n')
#Judge whether you are a member
money=float(input('Please enter your purchase amount:'))
if a=='y':#member
    if money>=200:
        print('The payment amount is',money*0.8)
    elif money>=100:
        print('The payment amount is',money*0.9)
    else:
        print('The payment amount is',money)
else:  #Non member
    if money>=200:
        print('The payment amount is',money*0.95)
    else:
        print('The payment amount is',money)

        #Pass statement pass can be used as a placeholder

Conditional expression

#Conditional expression
'''Enter two numbers and compare the size of the two numbers'''
num1=int(input('Please enter the first number'))
num2=int(input('Please enter the second number'))
'''if num1>=num2 :
    print(num1,"Greater than or equal to",num2)
else:
    print(num1,'less than',num2)
    This is the general way of writing'''
print('Conditional expression comparison size')
print(str(num1)+'Greater than or equal to'+str(num2)  if num1>=num2 else str(num1)+'less than'+str(num2))

Why learn object Boolean values

#On why to learn Boolean values of objects
age=int(input('Please enter your age:'))
if age:
    print(age)
else:
    print('Age is',age)#The reason why this code can run is that the Boolean value of 0 is false. You can directly put the object in the conditional expression
   

Chapter IV summary

Chapter V

1. Use of range() function

2.while loop

3. For in cycle

4. break .continue and else statements

5. Nested loop

Use of the range() function

   1. Used to generate a sequence of integers

   2. Three ways to create range objects

#Three ways to create range
'''The first creation method has only one parameter (only one number is given in parentheses)'''
r=range(10)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], start from 0 by default, and the default difference of 1 is called step size
print(r)#range(0,10)
print(list(r))#It is used to view the integer sequence in the range object. List means list

'''The second creation method gives two parameters (two numbers in parentheses)'''
r=range(1,10)#The starting value is set, starting from 1 and ending at 10. The interval is open, and the default step is 1
print(list(r))
'''The third creation method gives three parameters'''
r=range(1,10,2)#range(start,stop,step)
print(list(r))

'''Interpret whether the specified integer exists in the sequence, in,not in'''
print(10 in r)#false 10 is not in this integer sequence
print(9 in r)
print(10 not in r)

  3. The return value is an iterator object

  4. Advantages of range type: no matter how long the sequence represented by the range object is, the space occupied by all range objects is the same, because only start stop step is required. Only when the range object is used, the relevant elements in the sequence will be calculated

  5.in and not in determine whether the specified integer exists (does not exist) in the integer sequence

Cyclic structure

1. Repeatedly doing the same thing is called a cycle

2. Flow chart of cycle structure

3. Classification of cycles

·whlie

·for-in

4. Grammatical structure

 5. The difference between the selection structure if and the loop structure while

·if is judged once, and one line is executed when the condition is true

·while is to judge n+1 times, and execute n times if the condition is true

whlie cycle

#while loop in conditional expression
a=1
#Judgment condition expression
while a<10:
    #Execution condition executor
    print(a)
    a+=1
'''if It is judged once, and the condition is true Execute one line
    while It's judgment N+1 Times, if True implement N second'''

#Apply a wave
#Calculate the cumulative sum between 0 and 4
'''Four step cycle method
 initialize variable
 Conditional judgment
 Condition executor (condition is) True (code executed when)
Change variable
 Summary: the initialized variable is the same as the condition judgment variable and the changed variable'''
sum=0
a=0
while a<5:
    sum+=a
    a+=1
print(sum)

Practice and mistakes

#Calculate the even sum of one to 100
a=1
sum=0
while a<101:
    if a%2==0:
        sum+=a
    a+=1
print(sum)



'''Error 1'''
#Calculate the even sum between 1 and 100
a=0
sum=0
while a<101:
  a+=2
  sum+=a
print(sum)
#The calculation result is 2652, 102 more than the correct result


'''Error 3'''
#Forget it, I don't understand very well. It's really difficult. I'm not good at math. I may not be suitable for programming

for-in Loops

The 1.in expression takes values from (string, sequence) in turn, which is also called traversal

2. The object traversed by for in must be an iteratable object

3. Syntax structure of for in

for custom variable in iteratable object: loop body

4. Execution diagram of for in

5. There is no need for custom variables in the loop body. You can replace the custom variables with underscores

#for in loop
for item in 'python':  #The first IC takes out P, assigns p to item, and outputs item
    print(item)

#range () produces a sequence of integers, - "is also an iteratable object
for i in range(10):
    print(i,'hhh')

#If you do not need a custom variable in the loop body, you can write the custom variable as_
for _ in range(5):
    print('hhhhh')

practice

#Use the for loop to calculate the even sum between 1 and 100
sum=0
for item in range(1,101):
    if item%2==0:
        sum+=item
print(sum)
#Output the number of daffodils between 100 and 999
for item in range(100,1000):
    ge=item%10
    shi=item//10%10
    bai=item//100
    print(ge,shi,bai)
    if ge**3+shi**3+bai**3==item:
      print(item)

break statement

Used to end a loop structure, usually used with the branch structure if

​
'''Enter the password from the keyboard up to 3 times. If it is correct, the cycle will end'''
for item in range(3):
    pwd=input('Please input a password:')
    if pwd=='8888':
        print('The password is correct')
        break
    else:
        print('Incorrect password')

​

continue statement

It is used to end the current loop and enter the next loop. It is usually used together with if in the branch structure

#Process control statement continue
'''Multiple of all five between 1 and 50 is required
5 The common denominator of multiples of is that the remainder of 5 is 0'''
for item in range(1,51):
    if item%5==0:
        print(item)

print('------------use continue')
for item in range(1,51):
    if item%5!=0:
        continue
    print(item)

'''break It's over, continue Will continue'''

else statement

   

#else can also be used with for and while
for item in range(3):
    pwd=input('Please input a password:')
    if pwd=='8888':
        print('The password is correct')
        break
    else:
        print('Incorrect password')
else:
    print('Sorry, your three chances have been used up')
a=0
while a<3:
    pwd=input('Please input a password')
    if pwd=='8888':
        print('The password is correct')
        break
    else:
        print('Incorrect password')
        a+=1
else:
    print('Your opportunity has run out')

'''To sum up, it's the conditional executor and some loops,'''

Nested loop

Another complete loop structure is nested in the loop structure, in which the inner loop is executed as the loop body of the outer loop

#Nested loop
'''Print a three row four column*column'''
for i in range(1,4):
    for j in range(1,5):
        print('*',end='\t')
    print()



#Make a 99 multiplication table
for a in range(1,10):
    for b in range(1,a+1):
        print(a,'*',b,'=',a*b,end='\t')
    print()

break and continue in the double loop are used to control the loop of this layer

#Application of process control statements break and continue in double loop
for i in range(5):
    for j in range(1,11):
        if j%2==0:
            #break
            continue
        print(j,end='\t')
    print()

Chapter V knowledge summary

Chapter VI

1. Create and delete list

2. Query list

3. Addition, deletion and modification of list elements

4. Sorting of list elements

5. List derivation

1, Creation and characteristics

'''The first way to create a list,[]'''
lst=['hello','world',98]
print(lst)#List elements are sorted in order
print(lst[0],lst[-3])#Index map unique data
#Lists can store duplicate data
#Mixed storage of any data type
#Dynamically allocate and reclaim memory as needed
'''The second way to create a list is to use built-in functions list()'''
lst2=list(['hello','world',98])

2, Query operation of list

Gets the index of the specified element

​
'''Gets the index of the specified element'''
lst=['hello','world','89','hello']
print(lst.index('hello'))#If there are the same elements in the list, only the index of the first element of the same element in the list is returned
#print(lst.index('python'))#value error python is not in the list
#print(lst.index('hello',1,3))#Still wrong, because the open range is not in this range
print(lst.index('hello',1,4))#That's it


Gets the specified element in the list

​
'''Gets the specified element in the list'''

lst2=['hello','world',898,'hello','world',9382938]
print(lst2[2])#Forward index, from 0 to n-1
print(lst2[-3])#Negative index, from - n to - 1
#print(lst2[9])#Out of range, error reported

​

​

Get multiple elements in the list (slice operation)

'''Gets the form of multiple elements in the list[start:stop:step]Left closed right open'''
lst=[10,20,30,40,50,60,70,80]
#start1 stop6 step1
print(lst[1:6:1])
print(lst[1:6:2])
print(lst[:6:2])
print(lst[2::2])
print(lst[::])
print(lst[::-1])#Reverse order
print(lst[7:2:-1])

Judgment and traversal of list elements

'''Judgment and traversal of list elements'''
print(10 in lst)
print(10 not in lst)#Judge the specified element

#Traversal, for iteration variable in list name
for item in lst:
    print(item)

III

Addition of list elements

'''Add operation of list element'''
#Add an element append at the end of the list
lst=[10,20,30]
print('Before adding elements',lst)
lst.append(100)
print('After adding elements',lst)


#Add at least one element, extend, to the end of the list
lst2=['hello','Zhu Guoxu']
lst.append(lst2)
print(lst)#lst2 is added to the end of the list as an element
#x adds multiple elements to the end of the list at one time with extend
lst.extend(lst2)
print(lst)

#Add an element insert anywhere in the list
lst.insert(1,20)
print(lst)


#Slice and add at least one element anywhere in the list
lst3=['hahahha','My good baby']
lst[1:]=lst3
print(lst)
lst[1:2]=lst3
print(lst)

delete

'''Deletion of list elements'''
#remove, delete only one element at a time, delete the first element by repeating the element value, and display valueerror if the element does not exist
lst=[10,20,30,40,20]
lst.remove((20))
print(lst)


#pop deletes an element on the specified index. If the specified index does not exist, an indexerror will be displayed. If the index is not specified, the last element in the list will be deleted
lst.pop(1)
print(lst)
lst.pop()
print(lst)


#Slicing, deleting at least one element at a time, will produce a new list object
lst=[1,3,22,4343,56,3]
new_lst=lst[1:4]
print('Original list',lst)
print('New list',new_lst)


#clear list del delete objects
lst.clear()
print(lst)
del lst
#print(lst) has been cleared at this time, so there will certainly be no problem

modify

​
#Modification of list elements
lst=[1,2,3,4]
lst[2]=100
print(lst)#Assigns a new value to the specified index element
lst[1:3]=[10,20,30,40]
print(lst)#Assigns a new value to the specified slice

4, Sorting of list elements

'''Sorting operation of list elements'''
lst1=[20,30,2,4,5,45]
print('List before sorting',lst1)
#Start sorting, call the sort method of the list object, in ascending order
lst1.sort()
print('Sorted list',lst1)

#Sort the elements in the list in descending order by specifying keyword parameters
lst1.sort(reverse=True)#reverse=True is a descending sort, and reverse=False is an ascending sort
print(lst1)
lst1.sort(reverse=False)
print(lst1)

#Sorting the list using the built-in function sorted will produce a new list object
lst1=[20,30,2,4,5,45]
print('Original list',lst1)
new_lst1=sorted(lst1)
print('New list',new_lst1)
#Sort the elements in the list in descending order by specifying keyword parameters
new1_lst1=sorted(lst1,reverse=True)
print(new1_lst1)



​

5, List generation

'''List generating formula (formula for generating list)   [i*i(An expression that represents a list element for i((custom variable) in range()]'''
lst2=[i for i in range(1,10)]
print(lst2)

lst2=[i*i for i in range(1,10)]
print(lst2)

#The element values in the list are 2, 4, 6, 8, 10
lst2=[i*2 for i in range(1,6)]
print(lst2)


lst2=[i for i in range(2,11,2)]
print(lst2)

Chapter VI summary

Keywords: Python

Added by mass on Tue, 18 Jan 2022 01:39:26 +0200