1, Process control
if Conditions to judge: What to do when the conditions are established
if condition: Operation when conditions are met else: Operation when conditions are not met
# Conditional judgment statement in python if / if else / if elif elif else # Switch is not supported in python Case conditional statement # if condition judgment: # Code executed when the condition is true # age = int(input('Please enter your age: ') # if age < 18: # Operation rules for comparing strings and numbers: = = the result is False= The result is True, and other comparison operations will report errors # print('No entry under the age of 18 ') # if...else statement # if judgment conditions: # Code executed when the condition is true # else: # Code executed when the condition is not true age = int(input('Please enter your age:')) if age < 18: print('Gambling is not good. Study hard and make progress every day') else: # Code executed when the condition of if is not met print('Macao's first online casino is online!')
if xxx1: Thing 1 elif xxx2: Thing 2 elif xxx3: Thing 3
When xxx1 is satisfied, execute event 1, and the entire if ends
When xxx1 is not satisfied, judge xxx2. If xxx2 is satisfied, execute event 2, and then the whole if ends. When xxx1 is not satisfied, xxx2 is not satisfied. If xxx3 is satisfied, execute event 3, and then the whole if ends
score = float(input('Please enter your grade:')) ```python # Multiple if statements. There is no association between statements # if 60 > score >= 0: # print('You trash ') # # if 80 > score >= 60: # print('normal ') # # if 90 > score >= 80: # print('not bad ') # # if 100 >= score >= 90: # print("great") # An IF Elif statement if 60 > score >= 0: print('You trash') elif 80 > score >= 60: print('So-so') elif 90 > score >= 80: print('Not bad') elif 100 >= score >= 90: print("Great") else: print('You're dirty, you cheat!')
4.if statement nesting
if Condition 1: Things that meet condition 1 do 1 Things that meet condition 1 2 if Condition 2: Things 1 that meet condition 2 Things that meet condition 2 Outer if Judgment can also be if-else Inner if Judgment can also be if-else Select according to the actual development situation
# Nested if in if statement # In python, forced indentation is used to represent the structure between statements ticket = input('Have you bought a ticket?Y/N') if ticket == 'Y': print('After buying the ticket, you can enter the station') safe = input('Whether the security check is passed?Y/N') if safe == 'Y': print('Pass the security check and enter the waiting room') else: print('The station entered, but the security check failed') else: print('I didn't buy a ticket. Get out')
5. Guessing game
import random player = input('Please enter: scissors(0) stone(1) cloth(2):') player = int(player) # Generate random integers: one of 0, 1 and 2 computer = random.randint(0,2) # Used for testing #print('player=%d,computer=%d',(player,computer)) if ((player == 0) and (computer == 2)) or ((player ==1) and (computer == 0)) or ((player == 2) and (computer == 1)): print('Win, ha ha, you're great') elif player == computer: print('Draw, not another one') else: print('If you lose, don't go, wash your hands and come on until dawn')
6.for. . . in cycle
# The for loop in python refers to for In cycle. It is different from for in C language # For statement format: for ele in iterable # The range built-in class is used to generate an integer sequence (list) of a specified interval # Note: in must be followed by an iteratable object!!! # Currently contacted iteratable objects: string, list, dictionary, tuple, set, range for i in range(1, 11): print(i) # for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: # print(x) for y in 'hello': print(y) # for m in 10: # in must be followed by a knockable object # print(m) z = 0 # Define a variable to hold the sum of all numbers for j in range(1, 101): z += j print(z)
1. Introduction to string
A string can be understood as an ordinary piece of text. In python, quotation marks are used to represent a string. Different quotation marks will have different effects.
a = "I'm Tom" # A pair of double quotation marks b = 'Tom said:"I am Tom"' # A pair of single quotation marks c = 'Tom said:"I\'m Tom"' # Escape character d = '''Tom said:"I'm Tom"''' # Three single quotes e = """Tom said:"I'm Tom" """ # Three double quotes
The data in double quotation marks or single quotation marks is a string
If you use a pair of quotation marks to define a string, you can use escape characters when there is a symbol conflict
A string defined with three single and double quotation marks can wrap any text
Escape character is a part of the formal grammar of many program languages, data formats and communication protocols. Use \ to represent an escape character. The common escape characters and their meanings are shown in the following table:
Escape character meaning
\r moves the current position to the beginning of the line
\n moves the current position to the beginning of the next line
\t is used to represent a tab character
\Represents a backslash character
’Used to display a single quotation mark
"Used to display a double quotation mark
2. Introduction to slicing
Slicing refers to the operation of intercepting part of the operated object. String and tuple operations are supported.
Syntax of slice: [start: end: step], or simplify the use of [start: end]
# Index is to get an element by subscript # Slicing is to remove a segment of elements by subscript s = 'Hello World!' print(s) print(s) # o the fourth element in the string print(s[3:7]) # lo W contains subscript 3, excluding subscript 7 print(s[:]) # Hello World! The default step size is 1 for all elements without start and end bits print(s[1:]) # ello World! Start with subscript 1 and take out all subsequent elements (no end bit) print(s[:4]) # Hell starts from the start position and takes the previous element with subscript 4 (excluding the end bit itself) print(s[:-1]) # Hello World starts from the starting position and gets the penultimate element (excluding the end bit itself) print(s[-4:-1]) # rld starts from the penultimate element and gets the penultimate element (excluding the end bit itself) print(s[1:5:2]) # el starts with subscript 1 and takes the previous element with subscript 5 in steps of 2 (excluding the end bit itself) print(s[7:2:-1]) # ow ol starts with the element with subscript 7 (including the element with subscript 7), and reverses to the element with subscript 2 (excluding the element with subscript 2) # Fast inversion of python string print(s[::-1]) # ! dlroW olleH takes value from back to front in steps of 1
3. Common operations of string
① The len function can get the length of the string.
mystr = 'It's sunny today. It's a beautiful scenery everywhere' print(len(mystr)) # 17 get the length of the string
② Find find
Finds whether the specified content exists in the string. If it exists, it returns the index value of the start position of the content for the first time in the string. If it does not exist, it returns - 1
S.find(sub[, start[, end]]) -> int
mystr = 'It's sunny today. It's a beautiful scenery everywhere' print(mystr.find('Good scenery')) # 10 Where is "good" when "good scenery" first appears print(mystr.find('Hello')) # -1 'hello' does not exist, return - 1 print(mystr.find('wind', 12)) # 15 start with subscript 12 to find 'wind', find the location of the wind, and try 15 print(mystr.find('Scenery',1,10)) # -1 search "scenery" from subscript 1 to 12. If it is not found, return - 1
③ rfind is similar to the find() function, but it starts from the right.
mystr = 'It's sunny today. It's a beautiful scenery everywhere' print(mystr.rfind('good')) # 14
3. String operator
① The addition operator can be used between strings to splice two strings into one string. For example, the result of 'hello' + 'world' is' hello world '
② You can multiply between strings and numbers, and the result is to repeat the specified string multiple times. For example, the result of 'hello' * 2 is hello hello
③ If the comparison operator is used to calculate between strings, the corresponding encoding of characters will be obtained and then compared.
In addition to the above operators, the string does not support other operators by default.
1. Format of list
Define the format of the column: [element 1, element 2, element 3,..., element n]
The type of variable tmp is list
tmp = ['xiaoWang',180, 65.0]
The elements in the list can be of different types
2. Get list elements using Subscripts
namesList = ['xiaoWang','xiaoZhang','xiaoHua'] print(namesList) print(namesList) print(namesList)
3. Add elements to the list
① append adds the new element to the end of the list
#There are 3 variables defined by default A = ['xiaoWang','xiaoZhang','xiaoHua'] print("-----List before adding A Data-----A=%s" % A) #Prompt, and add elements temp = input('Please enter the name of the student to be added:') A.append(temp) print("-----After adding, the list A Data-----A=%s" % A)
② insert(index, object) inserts the element object before the index at the specified position
strs = ['a','b','m','s'] strs.insert(3,'h') print(strs) # ['a', 'b', 'm', 'h', 's']
③ extend allows you to add elements from another collection to the list one by one
a = ['a','b','c'] b = ['d','e','f'] a.extend(b) print(a) # ['a', 'b', 'C','d ',' e ',' f '] add b to a print(b) # The contents of ['d','e','f'] b remain unchanged
- Modify element
When modifying an element, assign a value to the specified list subscript.
#Define variable A, which has 3 elements by default A = ['xiaoWang','xiaoZhang','xiaoHua'] print("-----List before modification A Data-----A=%s" % A) #Modify element A = 'xiaoLu' print("-----After modification, the list A Data-----A=%s" % A)
3. Find elements
● in (exists). If it exists, the result is true; otherwise, it is false
● not in. If it does not exist, the result is true; otherwise, it is false
#List to find nameList = ['xiaoWang','xiaoZhang','xiaoHua'] #Gets the name the user is looking for findName = input('Please enter the name you want to find:') #Find out if it exists if findName in nameList: print('The same name was found in the list') else: print('Can't find')
4. Delete element
▲ del: delete according to subscript
▲ pop: delete the last element
▲ remove: delete according to the value of the element
masters = ['Wang Zhaojun', 'Zhen Ji', 'Diao Chan', 'Daji', 'Xiao Qiao', 'Da Qiao']
# There are three related methods to delete data: pop remove clear # The pop method will delete the last data in the list by default and return this data # pop can also pass in the index parameter to delete the data at the specified location x = masters.pop(3) print(masters) # ['Wang Zhaojun', 'Zhen Ji', 'Diao Chan', 'Xiao Qiao', 'Da Qiao'] # remove is used to delete the specified element masters.remove('Little Joe') # masters.remove('daji ') if the data does not exist in the list, an error will be reported print(masters) # You can also delete a data using del del masters print(masters) # Clear is used to clear a list masters.clear() print(masters) # a = 100 # del a # print(a) tanks = ['Arthur', 'Cheng Yaojin', 'Shield mountain', 'Fei Zhang', 'Lian Po', 'Cheng Yaojin'] # Query related methods print(tanks.index('Shield mountain')) # 2 # print(tanks.index('zhuang Zhou ')) will report an error if the element does not exist print(tanks.count('Cheng Yaojin')) # 2 # in operator print('Fei Zhang' in tanks) # True print('Su lie' in tanks) # False # Modify element # Using subscripts can directly modify the elements in the list tanks = 'Armor' print(tanks)
5. List traversal
# Traversal: access all the data you want. Traversal is for iteratable objects # while loop traversal / for In loop traversal killers = ['Li Bai', 'King Lanling', 'Han Xin', 'Zhao Yun', 'Acor ', 'Sun WuKong'] # for... The essence of the in loop is to constantly call the next method of the iterator to find the next data for k in killers: print(k) i = 0 while i < len(killers): print(killers[i]) i += 1
6. Nesting of lists
import random # Define a list to hold 3 offices offices = [,,] # Define a list to store the names of 8 teachers names = ['A','B','C','D','E','F','G','H'] i = 0 for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for tempNames in offices: print('office%d The number of people:%d'%(i,len(tempNames))) i+=1 for name in tempNames: print("%s"%name,end='') print("\n") print("-"*20)
7. Copy the list
① Using the copy method of the list, you can directly copy the original list into a new list. This copy method is shallow copy.
② In addition to using the copy method of the list, Python also provides a copy module to copy an object. The copy module provides two methods: shallow copy and deep copy. They are used in the same way, but the execution effect is different.
● shallow copy refers to the top-level copy of an object. The popular understanding is that the reference is copied, but the content is not copied.
● deep copy is a recursive copy of all levels of an object.
x = [100, 200, 300] # x and y point to the same memory space and will affect each other y = x # The equal sign is the assignment of the memory address # Copy method can be called to copy a list # The new list has the same contents as the original list, but points to different memory spaces z = x.copy() x = 1 print(z) # In addition to using the copy method that comes with the list, you can also use the copy module to copy import copy a = copy.copy(x) # The effect is equivalent to x.copy(), which is a shallow copy # Deep copy # A slice is actually a shallow copy names1 = ['Zhang San', 'Li Si', 'Wang Wu', 'jack'] names2 = names1[::] names1 = 'jerry' print(names2)