Process control
Process control is the control process, specifically refers to the execution process of the control program, and the execution process of the program is divided into three structures:
-
Sequential structure: run from top to bottom (the code we wrote before is sequential structure)
-
Branch structure: different processes may be executed according to different conditions during operation (if judgment is used)
-
Loop structure: some code needs to be executed repeatedly during operation (using while and for)
Branch structure: if judgment
Must know must know:
- 1. Conditions are converted to Boolean values, which determine whether the code is executed
- 2. Indents are used in python to represent dependencies of code
- 3. Not all code can have subcodes
- 4. Multiple lines of subcode belonging to one of your codes must be indented the same amount
- 5. In python, it is recommended to use the same indentation (four spaces represent an indentation) to identify a group of code blocks (if the end of the previous line of code is a colon, the next line of code must be indented)
What is a branch structure
The branch structure is to execute the sub code corresponding to different branches according to the true or false conditions
Why use a branch structure
In order to make the computer do different things according to the judgment results of conditions like people
Implement branch structure with if keyword
if Condition 1: ... Sub code block executed after condition 1 is true elif Condition 2: ... The sub code block executed after condition 1 is not true and condition 2 is true else: ... If the above conditions are not met, go this section
be careful:
-
The condition can be any expression, but the execution result must be Boolean. In if judgment, all data types will be automatically converted to Boolean
- None, 0, null (empty string, empty list, empty dictionary, etc.) the Boolean value converted to is False
- The rest are True
Single if branch structure
if condition: ... Sub code block executed after the condition is established print("end...") # Case: young man under 22 age = 20 if age < 22: print("A guy with no hair")
if..else (dual branch)
if condition: ... Sub code block executed after the condition is established else: ... if If the conditions are not established, go this section # Case: guess age age = 22 if age < 20: print("Hello, young man") else: print("Stupid")
if...elif...else (multi branch)
if Condition 1: ... Sub code block executed after condition 1 is true elif Condition 2: ... The sub code block executed after condition 1 is not true and condition 2 is true elif Condition 3: ... The sub code block executed after condition 1 and 2 are not true and condition 3 is true else: ... If none of the above conditions holds, go this paragraph # Case: # If achievement >= 90: excellent # If achievement >= 80 And< 90: good # If achievement >= 70 And< 80: ordinary # Other conditions: very poor score = 83 if score >= 90: print("excellent") elif score >= 80: print("good") elif score >= 70: print("ordinary") else: print("Very bad")
Nesting of if judgment
# We must combine pictures and texts to digest, understand and absorb # Case: continue on the basis of blind date. If hand in hand succeeds, then: together, otherwise... age = 26 height = 165 weight = 99 is_success = True if age < 28 and height > 160 and weight < 100: print('Can my little sister hold hands') # Judge whether the little sister will hold hands if is_success: print('It's dark at dinner and movies...') else: print('Fuck your sister's pervert!') else: print('it's a pity')
Loop structure: while loop
-
What is a while loop
- Loop is to do something repeatedly. while loop is the first loop mechanism provided by Python, which is called conditional loop
-
Why is there a while loop
- In order to control computers, they can do something repeatedly like people
Basic syntax of while loop
while condition: ... The sub code block executed by the loop after the condition is established """ while Operation steps: 1,If the condition is true, the sub code blocks are executed in turn 2,Judge the condition again after execution. If the condition is True The sub code block is executed again if the condition is False,Then the cycle ends """ while True: # 1.Get the user name and password entered by the user username = input('enter one user name>>>:') password = input('Please input a password>>>:') # 2.Determine whether the user name and password are correct if username == 'jack' and password == '123': print('Login succeeded!') else: print('Login failed, please re-enter!') # Note: dead cycle--->The condition is always True
Two ways to end a while loop
Method 1: Global flag bit
- Feature: it will not take effect until the body code of this cycle is run, and the judgment conditions of the next cycle
# Use of flag bits count = 0 flag = True while tag: if count == 5: flag = False # Change the condition to False print(i) count += 1
Mode 2: break
- Feature: break immediately ends the while loop of this layer
count = 0 tag = True while tag: if count == 5: # tag = False break print(i) count += 1
while nesting
while loop nesting + use of global flag bits
- For nested multi-layer while loops, if our purpose is to directly exit the loops of all layers at a certain layer, there is a trick. The "global flag bit" makes the conditions of all while loops use the same variable, and the initial value of the variable is True. Once the value of the variable is changed to False at a certain layer, the loops of all layers end
flag = True while flag: # First layer circulation while flag: # Second layer circulation flag = False # tag Become False,All while The conditions of the cycle become False # Case: flag = True while flag: inp_user = input("enter one user name>>>: ") inp_pwd = input("Please input a password>>>: ") if inp_user == "jack" and inp_pwd == "123": print('Login succeeded') # break flag = False else: print('Wrong user name or password')
Use of while loop nesting + break
- If the while loop is nested in many layers, you need to have a break in each layer of the loop to exit each layer of the loop
while True: # First layer circulation while True: # Second layer circulation while True: # Third layer circulation break # Terminate the third layer cycle break # Terminate the second layer cycle break # Terminate the first layer cycle # Case: while True: inp_user = input("enter one user name>>>: ") inp_pwd = input("Please input a password>>>: ") if inp_user == "jack" and inp_pwd == "123": print('Login succeeded!') while True: print(""" 0 sign out 1 withdraw money 2 deposit 3 transfer accounts """) choice = input("Please enter your command number:") if choice == "0": break elif choice == "1": print("Withdrawing money...") elif choice == "2": print("Depositing...") elif choice == "3": print("Transferring...") else: print("The input instruction does not exist") break else: print('Wrong user name or password')
while+continue: skip this cycle and directly enter the next cycle
# use while Loop print out 0-5 But do not print 2 and 4 # 1.Define a starting variable count = 0 # 2.loop while count < 6: if count == 2 or count == 4: count += 1 continue # continue After the same level, don't write code, and it won't run # 3.Print the value of the variable print(count) # 4.Variable value increases by 1 count += 1 """ continue It will let the loop body code directly return to the condition judgment for re judgment """ # Case: while True: inp_user = input("username>>>: ") inp_pwd = input("password>>>: ") # Determine whether the user name and password are correct if inp_user == "jack" and inp_pwd == "123": print('Login succeeded') # Enter the correct password and log in successfully break # End cycle else: print('Wrong user name or password') # continue # Be sure not to add it to the last step
while+else: the sub code block of else will run when the while loop dies normally. It is called normal death if it is not killed by break
# Case 1: normal death and normal circulation count = 0 while count < 5: if count == 2: count += 1 continue print(count) count += 1 else: print('====>') # Case 2: abnormal death, if it is break,It won't be executed else Statement of count = 0 while count < 5: if count == 2: break print(count) count += 1 else: print('====>')
Dead loop: condition is always True
while True: print(1) """Dead circulation will make CPU Extremely busy and even running"""
Small exercise:
""" Age guessing game General requirements Users can guess wrong three times. If they guess right in the process, they can exit directly Pull up requirements After three opportunities are used up, the user will be prompted whether to continue trying. If yes, another three opportunities will be given. Otherwise, it will end directly """ real_age = 18 # Define fixed age variables count = 0 # Define input times variable while True: # Three opportunities will be executed if count == 3: choice = input("Three opportunities have been used up! Continue?\n Please enter again'q',Exit, please enter't'>>>:") if choice == 'q' or choice == 'Q': count = 0 # Set the number of guesses to 0 else: print('The game is over'.center(35, '=')) break print('Age guessing game'.center(35, '*')) age = int(input('Please enter age>>>: ')) if age < real_age: print('Harm! Guess small, you also have:%s A chance!' % (2 - count)) elif age > real_age: print('Harm! Guess big, you also have:%s Second chance,!' % (2 - count)) else: print('Good guy, you guessed right. That's great!') break count += 1
Loop structure: for loop
-
1. What is a for loop
- Loop is to do something repeatedly. for loop is the second loop mechanism provided by python
-
2. Why a for loop
- Theoretically, the while loop can do whatever the for loop can do
- The reason why there is a for loop is that the for loop is more concise in loop value (traversal value) than the while loop
for loop basic syntax
for Variable name in Iteratable object: # Iteratable objects can be strings, lists, dictionaries, tuples, and collections ... for Loop body code # Example 1 for i in ['a','b','c']: print(i) # Operation results a b c # Refer to example 1 for Operation steps of cycle # Step 1: from the list['a','b','c']Read out the first value and assign it to item(item='a'),Then execute the loop body code # Step 2: from the list['a','b','c']Read out the second value and assign it to item(item='b'),Then execute the loop body code # Step 3: Repeat the above process until the values in the list are read out for Basic usage of loop
# Case 1: traversing the list names = ["kevin", "tom", "jack", "lili", "lxx", "xxx"] for x in names: print(x) for x,y in [["name","kevin"],["age",18],["gender","male"]]: # x,y = ['name', 'kevin'] print(x,y) # Case 2: traversing the dictionary dic={"k1":111,'K2':2222,"k3":333} for x in dic: # for The loop defaults to the dictionary key Assign to variable name k print(x,dic[x]) # Case 3: traversal string for x in "hello": print(x) msg="you can you up,no can no bb" for x in msg: print(x)
- Summarize the similarities and differences between for loop and while loop
-
1,Similarities: It's all a cycle, for Cycle what you can do, while Circulation can also be dry 2,Differences: while Loops are called conditional loops, and the number of loops depends on when the condition becomes false for The cycle is called"Value cycle",Number of cycles depends on in Number of values contained after
-
for+break: the same as the while loop
for i in [11,22,33,44,55]: if i == 33: break print(i)
for+continue: same as while loop
for i in [11,22,33,44,55]: if i == 33: continue print(i)
for+else: same as while loop
for i in [11,22,33,44,55]: if i == 33: break print(i) else: print('++++++++>')
range keyword
for + range control cycle times: range()
- There are limitations in placing a data type directly after in to control the number of cycles:
- When the number of cycles is too many, the format of the value contained in the data type needs to be increased
# range Function introduction # First kind:A parameter starts from 0, regardless of the head and tail for i in range(10): print(i) # Second:Two parameters customize the starting position, regardless of the head and tail for i in range(4, 10): print(i) # Third:The third number of the three parameters is used to control the equal difference value for i in range(2, 100, 10): print(i) """ Expand knowledge https://movie.douban.com/top250 page 1 https://movie. douban. com/top250? Start = 25 & filter = second page https://movie. douban. com/top250? Start = 50 & filter = page 3 https://movie. douban. com/top250? Start = 75 & filter = page 4 https://movie. douban. com/top250? Start = 0 & filter = guess first page """ base_url = "https://movie.douban.com/top250?start=%s&filter=" for i in range(0, 250, 25): print(base_url % i) """ range It is essentially different in different versions of the interpreter stay python2.X in range A list is generated directly stay python2.X One of them xrange It's also an iterator(Old sow) stay python3.X in range Is an iterator(Old sow) Save memory space python2.X in xrange namely python3.x Inside range """ # python2 Version demo ''' >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> >>> range(1,9) # 1...8 [1, 2, 3, 4, 5, 6, 7, 8] >>> >>> range(1,9,1) # 1 2 3 4 5 6 7 8 [1, 2, 3, 4, 5, 6, 7, 8] >>> range(1,9,2) # 1 3 5 7 [1, 3, 5, 7] ''' for i in range(30): print('===>') username='kevin' password='123' for i in range(3): inp_name = input('Please enter your account number:') inp_pwd = input('Please enter your password:') if inp_name == username and inp_pwd == password: print('Login succeeded') break else: print('Too many times of entering wrong account and password')
enumerate keyword
for + enumerate
i,name=(0,"kevin") for i,name in enumerate(["kevin","tom","jack"]): # [(0,"kevin"),(1,"tom"),(2,"jack")] print(i,name) for x in enumerate({"k1":111,"k2":2222,"k3":3333}): print(x)
Nested use of for loops
copy# for i in range(3): # for j in range(5): # print("*", end='') # print() for i in range(1, 10): for j in range(1, i + 1): print('%s*%s=%s' % (i, j, i * j), end=' ') print()