Python branches and loops

Branch and loop

Process control - controls the sequence of code execution

  1. Sequential structure: the code is executed from top to bottom, and each statement is executed only once. (default)

  2. Branch structure: select whether to execute or not to execute part of the code according to the conditions. (use if)

    age = int (input("Please enter your age:" ))
    if age >= 18:
        print ("adult")
    else:
    print("under age")
    
  3. Loop structure: make the code execute repeatedly (for, while)

    # for loop
    for _ in rang(10):
        print("Xiao Zhou")
    

if branch structure

  1. If single branch structure - if... Just...

    Syntax:

    if Conditional statement :
    	Code snippet (code that will be executed only if conditions are met)
    

    Problem solving: perform an operation when the conditions are met, and do not perform it when the addition is not met.

    explain:

    if -- keyword, fixed writing method

    Conditional statement - any expression with results, including: specific data, operation expression (except assignment operation), assigned variable and function call expression

    : -- Fixed writing method

    Code segment -- structurally, it is one or more statements (at least one) that maintain an indent with if;

    Logically, a code segment is a code that will be executed only when the condition is established

    [the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-K5aobOq7-1645102561291)(F: \ screenshot / day041.png)]

    #If the data saved by the variable is an integer, print 'Integer'
    num = 33
    if type(num) == int :
        print("integer")
    
    # Print 'pass' according to score
    score = float(input("Please enter your grade:"))
    if score >= 60.0:
        print("Qualified results")
    
  2. If double branch structure - if... Then... Otherwise

    Application scenario: perform an operation when a condition is met, and perform another operation when the condition is not met

    Syntax:

    if Conditional statement:
    	Code snippet 1 (code to be executed if conditions are met)
    else:
    	Code segment 2 (code to be executed when conditions are not met)
    
    #If the data saved by the variable is an integer, print 'Integer'
    num = 33
    if type(num) == int :
        print("integer")
    else:
        print("Not an integer")
    
    # Print 'pass' according to score
    score = float(input("Please enter your grade:"))
    if score >= 60.0:
        print("Qualified results")
    else:
        print("Unqualified results")
    
    # Judge the parity of an integer
    #Method 1:
    num = int(input("Please enter an integer:"))
    if num % 2 == 0:
        print(num,"It's an even number",sep='')
    else:
        print(num,"It's an odd number",sep='')
    #Method 2:
    num = int(input("Please enter an integer:"))
    if num % 2:			#A remainder of 1 represents True and a remainder of 0 represents False
        print(num,"It's an odd number",sep='')
    else:
        print(num,"It's an even number",sep='')
    
  3. If multi branch structure - if... If... If... If... If... Otherwise

    Application scenario: perform different operations according to different conditions

    Syntax:

    if Condition 1:
    	Code snippet 1
    elif Condition 2:
    	Code snippet 2
    elif Condition 3:
    	Code snippet 3
    ...						# elif can be any number; else can have or not
    else: 
    	Code snippet N
    
    #   Print scholarship amount based on score 
    # Method 1: after this method is completed, it will continue to judge the following operations
    	# Main solution: do different things according to different conditions
    score = float(input("Please enter your grade:"))
    if score > 90:
        print(2000)
    if 85< score <=90:
        print(1000)
    if 75 < score <=85:
        print(500)
    if 60 <= score <75:
        print(200)
    else:
        print(0)
    # Method 2:
    	# The main solution: do different things according to different conditions, but require the relationship between conditions. One condition holds, and the other condition never holds.
    score = float(input("Please enter your grade:"))
    if 90 < score:
        print(2000)
    elif 85 < score:
        print(1000)
    elif 75 < score:
        print(500)
    elif 60 <= score:
        print(200)
    else:
        print(0)
    

for loop

  1. Syntax:

    for variable in sequence:
        Circulatory body (Code to execute)
    

    Description: for - keyword; Fixed writing

    Variable - valid variable name (can be defined or undefined)

    in - keyword; Fixed writing

    Sequence - data of container data type; Container data types include string, list, dictionary, tuple, iterator, generator, range, etc.

    Loop body - one or more statements that maintain an indentation with for; The loop body is the code that needs to be executed repeatedly.

    Execution process: let variables take values from the sequence one by one until they are finished; Take a value and execute the loop body once

    The number of cycles of the for loop is related to the number of elements in the sequence.

  2. range function -- creates an arithmetic sequence (integer)

    range(N) --- # Generate an equal difference sequence of [0,N), and the difference is 1 
    range(M,N) --- # Generate an equal difference sequence of [M,N), and the difference is 1
    range(M,N,step) --- #Generate an equal difference sequence of [M,N), and the difference is step
    range(1,10,2) ---> # 1,3,5,7,9
    
  3. Two application scenarios:

    ① Cumulative summation:

    #Write code for 1 + 2 + 3 ++ Sum of 100
    #Method 1
    result = 0
    for i in range(1,101):
        result = result + i
        if i == 100 :
            print(result)
    #Method 2
    result = 0 
    for x in range(1,101):
        result += x
    print(result)
    
    # Factorial of 10
    #Method 1
    result = 1
    for i in range(1,11):
        result = result * i
        if i == 10 :
            print(result)
    #Method 2
    result = 1
    for i in range(1,11):
        result *= i
    print(result)
    

    ② Number of Statistics:

one
result = 1
for i in range(1,11):
result = result * i
if i == 10 :
print(result)
#Method 2
result = 1
for i in range(1,11):
result *= i
print(result)

② Number of Statistics:

Keywords: Python Back-end

Added by Coldman on Fri, 18 Feb 2022 00:23:00 +0200