Python process control

Process control

Process control is the control process, which specifically refers to the execution process of the control program, and the execution process of the program is divided into three structures: sequential structure (execution from top to bottom), branch structure (if judgment), and loop structure (while and for)

Branching structure

  • What is a branch structure

    Branch structure is to execute sub code blocks corresponding to different branches according to the true or false conditions.

  • Why branch structure

    Sometimes humans need to decide what to do according to conditions. For example, if it rains today, they should take an umbrella

Therefore, there must be a corresponding mechanism in the program to control the computer to have the ability of human judgment

  • How to use branch structure

    • if syntax

      Use the if keyword to implement the branch structure. The complete syntax is as follows:

      # 1. Single if branch structure
      
      """
      if condition:
      	The sub code block executed after the condition is established
      """
           
      # 2.if with else
      
      """
      if condition:
      	The sub code block executed after the condition is established
      else:
      	Sub code block executed when the condition is not tenable
      
      ps:if And else Subcode that combines the two will always execute only one
      """
        
      # 3.if elif else
      
      """
      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:
      	Conditions 1 and 2 are not true. The sub code block executed after condition 3 is true
      ...
      else:
      	None of the above conditions holds for the sub code block to be executed
      
      ps:elif There can be more than one
       When the three are used together, only one of the sub code blocks will be executed
      """
      
      # be careful:
      # 1. In Python, a group of code blocks is identified by the same indentation (four spaces represent an indentation, and four spaces are recommended in Python) to represent the dependency of the code. The same group of code will run from top to bottom
      
      # 2. The condition can be any expression, but the execution result must be Boolean
           # In the if judgment, all data types are automatically converted to Boolean types
           # 2.1 the Boolean value converted to is False in the three cases of none, 0 and null (empty string, empty list, empty dictionary, etc.)
           # 2.2. Other conditions are True 
          
      # 3. Not all code can have subcodes
      
      # 4. Multiple lines of subcode belonging to a code must maintain the same indentation
      
      # ps: Tip: if the end of the previous line of code is a colon, the next line of code must be indented
      
    • if application case

      Case 1:

      If: a woman's age is > 30 years old, then: call her aunt

      age_of_girl = 31
      if age_of_girl > 30:
          print('Hello, aunt')
      

      Case 2:

      If a woman's age is more than 30 years old, then: call her aunt, otherwise: call her little sister

      age_of_girl = 18
      if age_of_girl > 30:
          print('Hello, aunt')
      else:
          print('Hello, miss')
      

      Case 3:

      If: the woman's age > = 18 and < 22 years old, height > 170 and weight < 100 and is beautiful, then: confess, otherwise: aunt

      age_of_girl = 18
      height = 171
      weight = 99
      is_beautiful = True
      if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_beautiful == True:
          print('Confession...')
      else:
          print('Hello, aunt')
      

      Case 4:

      If: score > = 90, then: excellent

      If the score > = 80 and < 90, then: good

      If the score > = 70 and < 80, then: normal

      Other conditions: General

      score = input('>>: ')
      score = int(score)
      
      if score >= 90:
          print('excellent')
      elif score >= 80:
          print('good')
      elif score >= 70:
          print('ordinary')
      else:
          print('commonly')
      

      Case 5:

      if nesting

      # Continue on the basis of confession:
      # If the confession is successful, then: together
      # Otherwise: print...
       
      age_of_girl = 18
      height = 171
      weight = 99
      is_beautiful = True
      success = False
       
      if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_beautiful == True:
          if success:
              print('Successful confession,in harness')
          else:
              print('What love is not love,love nmlgb Love,love nmlg ah...')
      else:
          print('Hello, aunt')
      

    • if exercise

      # 1. Write a user login function. The user name is jason and the password is 123
      # If the user's input is correct, it will print. Welcome to the downstairs lounge, please! Otherwise, login fails
      """
      1.Write ideas and annotate the process first
      2.Then implement the code
      """
      
      # 1. Obtain the user name and password entered by the user
      username = input('username>>>:')
      password = input('password>>>:')
      # 2. Judge whether the user name and password are correct
      if username == 'jason' and password == '123':
      	print('Welcome, please take a seat downstairs!')
      else:
      	print('The user information you entered is incorrect. Login failed')
        
      # 2. Print different user identities according to different user names
      # jason: administrator tony: security personnel kevin: finance jack: Sales others: ordinary employees
      # 1. Get user name
      username = input('username>>>:')
      # 2. Judge user name and identity
      if username == 'jason':
      	print('administrators')
      elif username == 'tony':
      	print('Security personnel')
      elif username == 'kevin':
      	print('Finance')
      elif username == 'jack':
      	print('sale')
      else:
      	print('Ordinary staff')
      

Cyclic structure

  • What is a circular structure

    A loop structure is the repeated execution of a block of code

  • Why use circular structure

    Sometimes humans need to do something repeatedly, such as eating, sleeping, working, etc

    Therefore, there must be a corresponding mechanism in the program to control the computer, which has the ability of people's circular work

  • How to use loop structure

    • while loop syntax

      Python has two loop mechanisms: while and for. The while loop is called a conditional loop. The syntax is as follows:

      while condition:  
          Code 1
          Code 2
          Code 3
          ......
      # Running steps of while:
      # Step 1: if the condition is true, execute code 1, code 2, code 3
      # Step 2: after execution, judge the condition again. If the condition is True, execute again: Code 1, code 2, code 3,.... if the condition is False, the loop terminates
      

      Illustration: while loop

    • Application case of while loop

      Case 1: basic use of while loop

      User authentication program

      # The basic logic of the user authentication program is to receive the user name and password entered by the user, and then judge with the user name and password stored in the program. If the judgment is successful, the login is successful, and if the judgment fails, the account or password error is output
      username = "jason"
      password = "123"
       
      inp_name = input("Please enter user name:")
      inp_pwd = input("Please input a password:")
      if inp_name == username and inp_pwd == password:
          print("Login successful")
      else:
          print("The user name or password entered is incorrect!")
      # Generally, when the authentication fails, the user will be required to re-enter the user name and password for authentication. If we want to give the user three trial and error opportunities, the essence is to run the above code three times. You don't want to copy the code three times....
      
      username = "jason"
      password = "123"
       
      # First verification
      inp_name = input("Please enter user name:")
      inp_pwd = input("Please input a password:")
      if inp_name == username and inp_pwd == password:
          print("Login successful")
      else:
          print("The user name or password entered is incorrect!")
       
      # Second verification
      inp_name = input("Please enter user name:")
      inp_pwd = input("Please input a password:")
      if inp_name == username and inp_pwd == password:
          print("Login successful")
      else:
          print("The user name or password entered is incorrect!")
       
      # Third verification
      inp_name = input("Please enter user name:")
      inp_pwd = input("Please input a password:")
      if inp_name == username and inp_pwd == password:
          print("Login successful")
      else:
          print("The user name or password entered is incorrect!")
       
      # Even if you are Xiaobai, you think it's too low. You have to modify the function three times in the future. Therefore, remember, writing duplicate code is the most shameful behavior of programmers.
      # So how to make the program repeat a piece of code many times without writing duplicate code? Loop statements come in handy (implemented using a while loop)
       
      username = "jason"
      password = "123"
      # Record the number of error verifications
      count = 0
      while count < 3:
          inp_name = input("Please enter user name:")
          inp_pwd = input("Please input a password:")
          if inp_name == username and inp_pwd == password:
              print("Login successful")
          else:
              print("The user name or password entered is incorrect!")
              count += 1
      

      Case 2: use of while+break

      After using the while loop, the code is indeed much simpler, but the problem is that the user cannot end the loop after entering the correct user name and password. How to end a loop? This requires a break!

      username = "jason"
      password = "123"
      # Record the number of error verifications
      count = 0
      while count < 3:
          inp_name = input("Please enter user name:")
          inp_pwd = input("Please input a password:")
          if inp_name == username and inp_pwd == password:
              print("Login successful")
              break # Used to end the cycle of this layer
          else:
              print("The user name or password entered is incorrect!")
              count += 1
      

      Case 3: 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

      username = "jason"
      password = "123"
      count = 0
      while count < 3:  # First layer circulation
          inp_name = input("Please enter user name:")
          inp_pwd = input("Please input a password:")
          if inp_name == username and inp_pwd == password:
              print("Login successful")
              while True:  # Second layer circulation
                  cmd = input('Please enter your instructions>>>: ')
                  if cmd == 'quit':
                      break  # It is used to end the cycle of this layer, that is, the cycle of the second layer
                  print('run <%s>' % cmd)
              break  # It is used to end the cycle of this layer, that is, the cycle of the first layer
          else:
              print("The user name or password entered is incorrect!")
              count += 1
      

      Case 4: use of while loop nesting + tag (Global flag bit)

      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, that is, to make 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

      username = "jason"
      password = "123"
      count = 0
       
      tag = True
      while tag: 
          inp_name = input("Please enter user name:")
          inp_pwd = input("Please input a password:")
          if inp_name == username and inp_pwd == password:
              print("Login successful")
              while tag:  
                  cmd = input('>>: ')
                  if cmd == 'quit':
                      tag = False  # tag becomes False, and the conditions of all while loops become False 
                      break
                  print('run <%s>' % cmd)
              break  # It is used to end the cycle of this layer, that is, the cycle of the first layer
          else:
              print("The user name or password entered is incorrect!")
              count += 1
      

      Case 5: use of while+continue

      break represents the end of this layer cycle, while continue is used to end this cycle and directly enter the next cycle

      # Print all numbers between 1 and 10 except 7
      number = 11
      while number > 1:
          number -= 1
          if number == 7:
          	continue  # End this cycle, that is, the code after this cycle continue will not run, but directly enter the next cycle
          print(number)
      

      Case 6: use of while+else

      After the while loop, we can follow the else statement. When the while loop is executed normally and is not interrupted by break, the statement after else will be executed. Therefore, we can use else to verify whether the loop ends normally

      count = 0
      while count <= 5 :
          count += 1
          print("Loop",count)
      else:
          print("The loop is running normally")
      print("-----out of while loop ------")
      output
      Loop 1
      Loop 2
      Loop 3
      Loop 4
      Loop 5
      Loop 6
       The loop is running normally   # It was not interrupted by break, so this line of code was executed
      -----out of while loop ------
      

      If it is broken during execution, else statements will not be executed

      count = 0
      while count <= 5 :
          count += 1
          if count == 3:
              break
          print("Loop",count)
      else:
          print("The loop is running normally")
      print("-----out of while loop ------")
      output
      Loop 1
      Loop 2
      -----out of while loop ------  # Because the loop is broken by break, the output statement under else is not executed
      

      Exercise 1:

      Find the largest multiple of the number 7 between 1 and 100 (the result is 98)

      Exercise 2:

      Guess age

    • for loop syntax

      The second implementation method of the loop structure is the for loop, which can do all the things that the while loop can do. The reason why the for loop is used is that when the loop value (i.e. traversal value) is taken, the for loop is more concise than the while loop

      The syntax of the for loop is as follows:

      for Variable name in Iteratable object:  
          Code one
          Code two
          ...
       
      # Example 1
      for item in ['a', 'b', 'c']:
          print(item)
      # Operation results
      a
      b
      c
       
      # Refer to example 1 to introduce the operation steps of the for loop
      # Step 1: read out the first value from the list ['a','b','c '] and assign it to item (item ='a'), and then execute the loop body code
      # Step 2: read out the second value from the list ['a','b','c '] and assign it to item (item ='b'), and then execute the loop body code
      # Step 3: repeat the above process until the values in the list are read out
      

    • for loop application case

      Case 1: print numbers 0-5

      # Simple version: implementation of for loop
      for count in range(6):  # range(6) will generate 6 numbers from 0 to 5
          print(count)
       
      # Complex version: implementation of while loop
      count = 0
      while count < 6:
          print(count)
          count += 1
      

      Case 2: traversing the dictionary

      # Simple version: implementation of for loop
      for k in {'name':'jason','age':18,'gender':'male'}:  # By default, the for loop takes the dictionary key and assigns it to the variable name k
          print(k)
       
      # Complex version: the while loop can indeed traverse the dictionary, which will be described in detail in the iterator section
      

      Case 3: for loop nesting

      #Please print the following graphics in a for loop nested manner:
      *****
      *****
      *****
       
      for i in range(3):
          for j in range(5):
              print("*",end='')
          print()  # print() means line feed
      

      Note: break and continue can also be used for a for loop. The syntax is the same as that of a while loop

      Exercise 1:

      Print 99 multiplication table

      Exercise 2:

      Print pyramid

Added by cjdesign on Thu, 04 Nov 2021 23:35:35 +0200