Knot of the Day - 0916 Branches and Cycles Branches and Cycles

Python Basic Syntax - Branch and Loop

1. Process Control

  1. Sequential structure (default): Code is executed one at a time from top to bottom.
  2. Branch structure (if): When executing code, choose to execute a section of code based on the conditional results.
  3. Loop structure (for / while): repeat execution of a piece of code.

Example 1.1.1:

# Sequential structure

# Branch structure
age = int(input('Please enter your age:'))
if age <= 18:

# Cyclic structure
for _ in range(100)
    print('I LOVE YOU')

2.If branch

2.1 Single Branch (if branch)

When the code is executed, an operation is executed if a condition is met, otherwise a single branch structure is used when the operation is not executed.

Grammar: if condition: 
		Code snippet
# When the condition after if is met, the code is executed, otherwise it is not executed.


  • if: keyword, fixed writing;
  • Conditional statement: can be any expression that has a result, such as data, expression that has been assigned, operation expression, function call expression (assignment statement has no result and cannot be used as conditional statement);
  • Colon is fixed and must be in English;
  • Code snippet: One or more statements that remain indented with if are code that executes only when conditions are met.

Execution process: If xxx (conditional statement) then xxx (code snippet). First determine if the conditional statement is True (if the result of the conditional statement is not Boolean, convert it to Boolean and look again), if True, execute the code snippet, otherwise the code snippet will not execute.

Example 2.1.1:

if 55 + 58 >= 105:
    print('Congratulations', end= '')
print('Excellent') # The snippet executes regardless of the results of the above execution.

2.2 Double Branch Structure (if - else Branch)

When code is executed, an action is executed if a condition is met, otherwise another action is executed

Grammar: if Conditional statement:
         Code snippet 1 (the code that meets the criteria to execute)
         Code snippet 2 (code to execute if the condition is not met)
# One of the two code snippets must not execute.

Execution process: if (conditional statement) xxx (code snippet 1), otherwise xxx (code snippet 2)

Example 2.2.1:

# Print'odd'or'even' based on the value of the specified integer
# Method 1:
num = int(input('Please enter a number to query'))
if num % 2 == 0:
    print('Even numbers')
    print('Odd Number')
#Method 2: Less computation and less readability  
num = int(input('Please enter a number to query'))
if num % 2:
    print('Odd Number')
    print('Even numbers')

2.3 Multi-Branch Structure (if-elif-else Branch)

When executing code, different actions are performed according to different conditions.

Grammar:  if Condition 1:
          Code snippet 1  # If condition 1 is true, code snippet 1 is executed, and subsequent conditions are not judged, and the program ends directly.
       elif Condition 2:
          Code snippet 2  # If condition 1 is not established and condition 2 is established, the code snippet is executed, and subsequent conditions are not judged, and the program ends directly.
          Code snippet n  # If none of these conditions are valid, snippet n is executed.
# Each condition is established separately, that is, if one condition is established, the other conditions are absolutely not.

Example 2.3.1:

# Print'Excellent','Good','Medium','Pass','Fail'according to the score range
secor1 = float(input('Please enter your results:'))
if not 0 <= secor1 <= 100:
    print('Input error, please re-enter!')
elif secor1 >= 90:
    print('Your results are excellent!')
elif secor1 >= 80:
    print('Your results are medium!')
elif secor1 >= 70:
    print('Your results are good!')
elif secor1 >= 60:
    print('Your results pass!')
    print('You failed!')
# The code is as concise as possible, reducing redundant operations.

*** Special case: *** When multiple conditions are not independent, that is, when one condition is valid, the other conditions also need to be judged and acted upon. Multiple single-branch structures can be used to form a multi-branch structure.

Grammar: if Condition 1:
         Code snippet 1
      if Condition 2:
         Code snippet 2

2.4 Branch Nesting (if Nesting)

Nested if statement inside if statement

Grammar: if Condition 1:
        if Condition 2: #When condition 1 is true, condition 2 will be determined.
           Code snippet 1
        Code snippet 2

Example 2.4.1:

# Print'odd','even','multiple of'4'based on the specified number'
num1 = int(input('Please enter the number to query:'))
if num1 % 2 == 0:
    print('The number is even')
    if num1 % 4 == 0:
        print('This number is a multiple of 4')
    print('The number is odd')

In the example above, when the number is odd, it must not be a multiple of 4, so no further decision is needed. Therefore, branch nesting is used to reduce redundant operations and decisions.


3.1 for loop

Let a piece of code execute repeatedly.

Grammar: for variable in sequence:
          Circulatory body

Execution process: Variables are continuously taken from the sequence, and the loop body executes once for every value taken by the variable. The number of executions is only related to the number of elements in the sequence.


  • for: keyword, fixed writing;
  • Variable: The variable name, which is the same as the variable name that defines the variable (an identifier, but not a keyword);
  • in: keyword, fixed writing;
  • Sequence: Container data type, such as string, list, tuple, dictionary, collection, iterator, generator, range, etc.
  • : Fixed writing, write sequence colon;
  • Loop body: Structurally, it is one or more statements that maintain an indentation with for; logically, it is statements that need to be repeated.


for x in '1258':
    print(x, 'Hello')

Cyclic process:

First cycle: x ='1': print(x,'Hello') -"print('1','Hello')

Second cycle: x ='1': print(x,'Hello') -"print('2','Hello')

Third cycle: x ='1': print(x,'Hello') -"print('5','Hello')

Fourth cycle: x ='1': print(x,'Hello') -"print('8','Hello')

End of cycle!

Important functions in the for loop: range,

Range function: System function that produces a sequence of numbers in a specified range


  1. range(N): produces a sequence of numbers from 0 to N-1, [0, N], where N is a positive integer;
  2. range(M, N): To produce a sequence of numbers from M to N-1, [M, N), M and N must be integers and M < N;
  3. Range (M, N, step): [M, N), the step is step (increasing step each time starting with M). For example: range(1, 10, 2) - 1,3,5,7,9.

Example 3.1.1:

# Usage 1:
for x in range(2, 5):
    print(x, 555555)

# Usage 2:
for x in range(8):
    print(x, '--------')

# Usage 3:
for x in range(1, 10, 2):
    print(x, '--------')

Usage 1:

Usage 2:

Usage 3:

Common application routines:

  • Sum:
    1. Define a variable to hold the last sum;
    2. Use the variables in the for loop to pull out all the data that needs to be summed in turn.
    3. Each value taken by a variable in a loop adds a value to the variable that holds the sum.

Example 3.1.2:

# Find 1+2+3+...+100
sum1 = 0
for x in range(0, 101):
    sum1 += x
  • Number of statistics:
    1. Define a variable to hold the last number;
    2. Use the for loop statement to take out the data that needs to be judged in turn;
    3. For each data that meets the criteria, add 1 to the variable value.

Example 3.1.3:

# Count the number of even numbers between 20 and 100
# Method 1:
count = 0
for x in range(20, 101):
    if x % 2 == 0:
        count += 1

# Method 2:
count = 0
for x in range(20, 101, 2): # A sequence of equal deviations with a step length of 2. Under the current conditions, each value is even, reducing the operation.
    count += 1

Tags: Python Pycharm crawler

Posted on Thu, 16 Sep 2021 12:35:44 -0400 by tazdevil