08_Python_ Loop statement

Loop statement

loop

target

  • Three Processes of Procedure
  • for loop basic use
  • while loop basic use
  • break and continue
  • while loop nesting

01. Three Processes of Procedure

  • There are three processes in program development:

    • Sequence - Execute code from top to bottom in sequence
    • Branch - The branch that determines the code to execute based on conditions
    • Loop - let specific code execute repeatedly

02. for loop basic use

  • The purpose of loops is to repeat the execution of specified code
for i in range(n):
    Circulatory body
else:
    If the above for There was no interruption in the loop (0~N-1 No interruption occurred break),
    Then execute,If an interrupt occurs, it is not executed.

03. while Loop Basic Use

  • The purpose of loops is to repeat the execution of specified code

  • The most common scenario for a while loop is to have the code executed repeat a specified number of times

  • Requirements - Print Hello Python 5 times

  • Think - what if you want to print 100 times?

3.1 Basic syntax for while statements

Initial condition settings - usually counters that repeat execution

while condition(Determine whether the counter has reached the target number of times):
    What to do when the conditions are met 1
    What to do when the conditions are met 2
    When conditions are met, do 3
    ...(ellipsis)...
    
    treatment conditions(Counter + 1)

Be careful:

  • The while statement and indentation section are a complete block of code

The first while loop

demand

  • Print Hello Python 5 times
# 1. Define the number of repeats counter
i = 1

# 2. Use while to judge conditions
while i <= 5:
    # Code to repeat
    print("Hello Python")

    # Processing counter i
    i = i + 1

print("At the end of the cycle i = %d" % i)

Note: After the loop ends, the previously defined counter condition values still exist

Dead cycle

Due to programmer's reasons, forget to modify the loop's judgment inside the loop, causing the loop to continue executing, the program can not terminate!

3.2 Assignment Operator

  • In Python, variable values can be assigned using =
  • In order to simplify the coding of arithmetic operations, Python also provides a series of assignment operators corresponding to arithmetic operators.
  • Note: Spaces cannot be used in the middle of assignment operators
operatordescribeExample
=Simple assignment operatorc = a + b assigns a + b to c
+=Addition assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
//=Integer division assignment operatorc //= a is equivalent to c = c // a
%=Modulo (remainder) assignment operatorC%= A is equivalent to C = C% a
**=Power assignment operatorc **= a is equivalent to c = c ** a

Counting methods in 3.3 Python

There are two common counting methods, which can be called:

  • Natural Count (from 1) - More in line with human habits
  • Program Counting (from 0) - Almost all programming languages choose to start counting from 0

So when you write a program, you should try to get into the habit of counting loops starting at 0 unless you need something special

3.4 Cycle Calculations

In program development, there is often a need to utilize circular, repetitive computing

To meet this need, you can:

  1. Define a variable above while to hold the final calculation results
  2. Inside the loop, each cycle updates the previously defined variables with the latest calculations

demand

  • Calculate the cumulative sum of all numbers between 0 and 100
# Calculate the cumulative sum of all numbers between 0 and 100
# 0. Variables defining the final result
result = 0

# 1. Define an integer variable to record the number of loops
i = 0

# 2. Start the cycle
while i <= 100:
    print(i)

    # Each loop adds the result variable to the i counter
    result += i

    # Processing Counter
    i += 1

print("0~100 The sum of numbers between = %d" % result)

Demand Advancement

  • Calculates the cumulative sum of all even numbers between 0 and 100

Development steps

  1. Write a loop to confirm the number to be calculated
  2. Add a result variable to process the result inside the loop
# 0. Final result
result = 0

# 1. Counters
i = 0

# 2. Start the cycle
while i <= 100:

    # Judging Even Numbers
    if i % 2 == 0:
        print(i)
        result += i

    # Processing Counter
    i += 1

print("0~100 The result of summing even numbers between = %d" % result)

Usage of 3.5 for and while

for       1,Use when the number of iterations is determined
while     1,Use 2 when the number of iterations is determined and 2 when the number of iterations is not fixed

04. break and continue

break and continue are keywords specifically used in loops

  • When a break condition is met, exit the loop and do not execute subsequent duplicate code
  • Do not execute subsequent duplicate code when a continue condition is satisfied

break and continue are valid only for the current loop

4.1 break

  • During a loop, if a condition is met and you no longer want the loop to continue, you can use break to exit the loop
i = 0

while i < 10:

    # When a break condition is met, exit the loop and do not execute subsequent duplicate code
    # i == 3
    if i == 3:
        break

    print(i)

    i += 1

print("over")

break is valid only for the current loop

4.2 continue

  • During a loop, if you do not want to execute the loop code but do not want to exit the loop after a certain condition is met, you can use continue
  • That is, throughout the loop, there are only certain conditions that do not require the execution of the loop code and others that need to be executed
i = 0

while i < 10:

    # When i == 7, you don't want to execute code that needs to be repeated
    if i == 7:
        # Counters should also be modified before continue is used
        # Otherwise, an endless loop will occur
        i += 1

        continue

    # Repeated code
    print(i)

    i += 1

  • Note: When using continue, the code in the conditional processing section needs special attention, and an inadvertent deadlock occurs

continue is only valid for the current loop

05. while Loop Nesting

5.1 Loop Nesting

  • The while nesting is that there are whiles inside
while Condition 1:
    What to do when the conditions are met 1
    What to do when the conditions are met 2
    When conditions are met, do 3
    ...(ellipsis)...
    
    while Condition 2:
        What to do when the conditions are met 1
        What to do when the conditions are met 2
        When conditions are met, do 3
        ...(ellipsis)...
    
        Processing condition 2
    
    Processing condition 1

5.2 Circular Nested Walkthrough--Nine-nine Multiplication Table

Step 1: Print Stars Nested

demand

  • Output five consecutive lines in the console*, incrementing the number of each planet number in turn
*
**
***
****
*****
  • Print using string*
# 1. Define a counter variable, starting with the number 1, which makes looping easier
row = 1

while row <= 5:

    print("*" * row)

    row += 1

Step 2: Print small stars using circular nesting

Knowledge points enhance the use of print functions

  • By default, line breaks are automatically added at the end of content after the print function outputs content

  • If you don't want a line break at the end, add it after the output of the print function, end=""

  • Where "" can specify the output of the print function, and then continue what you want to display

  • The grammar format is as follows:

#print default format
print(self, *args, sep=' ', end='\n', file=None)

# No line breaks when output to console is complete
print("*", end="")

# Simple line break
print("")

end="" means that no line breaks will occur after the output to the console is complete

Assume Python does not provide a string of * operation stitching strings

demand

  • Output five consecutive lines in the console*, incrementing the number of each planet number in turn
*
**
***
****
*****

Development steps

  • 1>Complete simple output of 5 lines
  • 2>What should I do to analyze the * inside each row?
    • Each row shows the same number of stars as the current row
    • Nested with a small loop to handle star display for columns in each row
row = 1

while row <= 5:

    # Assume python does not provide a string*operation
    # Inside the cycle, add another cycle to print the stars for each row
    col = 1

    while col <= row:
        print("*", end="")

        col += 1

    # Add another line break after each planet number output is complete
    print("")

    row += 1

Step 3: Nine-nine Multiplication Table

Demand output ninety-nine multiplier table in the following format:

1 * 1 = 1	
1 * 2 = 2	2 * 2 = 4	
1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	
1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	
1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	
1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	
1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	
1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	
1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81

Development steps

    1. Print 9 rows of stars
*
**
***
****
*****
******
*******
********
*********
    1. Replace each * with the corresponding row multiplied by the column
# Define start line
row = 1

# Maximum 9 lines printed
while row <= 9:
    # Define Starting Column
    col = 1

    # Maximum Print row Column
    while col <= row:

        # end ='', means no line break after output
        # '\t'can output a tab in the console to help align when outputting text
        print("%d * %d = %d" % (col, row, row * col), end="\t")

        # Number of columns + 1
        col += 1

    # Line wrap after one line printing
    print("")

    # Number of rows + 1
    row += 1

Escape characters in strings

  • \t Outputs a tab in the console to help maintain vertical alignment when outputting text
  • \n Outputs a line break in the console

The function of tabs is to align text in columns vertically without using tables

Escape Characterdescribe
\\Backslash symbol
\'Single quotation mark
\"Double Quotes
\nLine Break
\thorizontal tab
\rEnter

5.3 Boxing Game

'''
Boxing game: man-machine battle! Two wins in three games
'''

moban = """
-----------------------------------------------------------------
                  Two wins in three games: man-machine boxing game
                  
                  Stone: 0, scissors: 1, cloth: 2
-----------------------------------------------------------------
"""
print(moban)
import random

p_count = 0  # Number of wins for a person
m_conut = 0  # Number of machine wins

while True:
    # Machine guessing, random number 0-2
    ran = random.randint(0, 2)
    if p_count == 2:
        print('This game wins, wins, wins two games first!')
        break
    elif m_conut == 2:
        print('Machine wins this game, win, win two games first!')
        break
    # Guess Boxing npu
    guess = int(input('Please enter: (Stone: 0, Scissors: 1, Cloth: 2)\n'))

    if (guess == 0 and ran == 1) or (guess == 1 and ran == 2) or (guess == 2 and ran == 0):

        print('Robots from this bureau:%s,This player wins!!!' % ran)
        p_count += 1
    elif (ran == 0 and guess == 1) or (ran == 1 and guess == 2) or (ran == 2 and guess == 0):
        print('Robots from this bureau:%s,This machine wins!!' % ran)
        m_conut += 1
    else:
        print('Robots from this bureau:%s,This round of tie!!!' % ran)

Keywords: Python Back-end

Added by thewooleymammoth on Thu, 03 Feb 2022 19:21:06 +0200