Python Basics_ 12 (cycle)

loop

target

  • Three processes of procedure
  • Basic use of while loop
  • break and continue
  • while loop nesting

01. Three processes of procedure

  • There are three process modes in program development:

    • Sequence - execute code sequentially from top to bottom
    • Branch -- determine the branch to execute code according to condition judgment
    • Loop -- repeats specific code

02. Basic use of while cycle

  • The function of the loop is to make the specified code execute repeatedly

  • The most common application scenario of while loop is to make the executed code execute repeatedly for a specified number of times

  • Requirements - Print 5 times Hello Python

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

2.1 basic syntax of while statement

Initial condition setting - usually a counter that is executed repeatedly

while condition(Judge whether the counter reaches the target number of times):
    Things to do when conditions are met 1
    What to do when the conditions are met 2
    What to do when the conditions are met 3
    ...(ellipsis)...
    
    treatment conditions (Counter + 1)

be careful:

  • The while statement and the indented part are a complete block of code

First while loop

demand

  • Print 5 times Hello Python
# 1. Define repetition 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("After the cycle i = %d" % i)

Note: after the loop ends, the value of the previously defined counter condition still exists

Dead cycle

Due to the programmer's reason, he forgot to modify the judgment conditions of the loop inside the loop, resulting in the continuous execution of the loop and the program cannot be terminated!

2.2 assignment operator

  • In Python, you can assign a value to a variable using =
  • In arithmetic operation, Python also provides a series of assignment operators corresponding to arithmetic operators in order to simplify code writing
  • Note: spaces cannot be used between assignment operators
operatordescribeexample
=Simple assignment operatorc = a + b assigns the operation result of a + b to c
+=Additive 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

2.3 counting method in Python

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

  • Natural counting (starting from 1) - more in line with human habits
  • Program counting method (starting from 0) - almost all program languages choose to count from 0

Therefore, when writing programs, we should try to form a habit: unless the requirements are special, the count of cycles starts from 0

2.4 cycle calculation

In the process of program development, we often encounter the need of using cyclic repeated calculation

In this case, you can:

  1. Define a variable above while to store the final calculation result
  2. Inside the loop body, each loop updates the previously defined variables with the latest calculation results

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 cycles
i = 0

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

    # In each cycle, the variable result is added to the counter i
    result += i

    # Processing counter
    i += 1

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

Advanced demand

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

Development steps

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

# 1. Counter
i = 0

# 2. Start cycle
while i <= 100:

    # Judge even number
    if i % 2 == 0:
        print(i)
        result += i

    # Processing counter
    i += 1

print("0~100 Even sum result between = %d" % result)

03. break and continue

break and continue are keywords specifically used in loops

  • When a certain condition is met, exit the loop and do not execute subsequent repeated code
  • continue when a condition is met, subsequent repeated code will not be executed

break and continue are only valid for the current loop

3.1 break

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

while i < 10:

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

    print(i)

    i += 1

print("over")

break is only valid for the current loop

3.2 continue

  • During the 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, in the whole loop, only some conditions do not need to execute the loop code, while other conditions need to be executed
i = 0

while i < 10:

    # When i == 7, you do not want to execute code that needs to be executed repeatedly
    if i == 7:
        # Before using continue, you should also modify the counter
        # Otherwise, an endless cycle will occur
        i += 1

        continue

    # Repeatedly executed code
    print(i)

    i += 1

  • Note: when you use continue, you need to pay special attention to the code in the condition processing part. If you are not careful, an endless loop will appear

continue is only valid for the current cycle

04. while loop nesting

4.1 loop nesting

  • While nesting means that there are still while in while
while Condition 1:
    Things to do when conditions are met 1
    What to do when the conditions are met 2
    What to do when the conditions are met 3
    ...(ellipsis)...
    
    while Condition 2:
        Things to do when conditions are met 1
        What to do when the conditions are met 2
        What to do when the conditions are met 3
        ...(ellipsis)...
    
        Treatment condition 2
    
    Treatment condition 1

4.2 loop nesting drill - 99 multiplication table

Step 1: print small stars with nesting

demand

  • Five consecutive lines * are output on the console, and the number of asterisks in each line increases in turn
*
**
***
****
*****
  • Print using string *
# 1. Define a counter variable. Starting from the number 1, the cycle will be more convenient
row = 1

while row <= 5:

    print("*" * row)

    row += 1

Step 2: print small stars using circular nesting

The knowledge points enhance the use of print function

  • By default, after the print function outputs the content, a new line is automatically added at the end of the content

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

  • Among them, you can specify the content you want to display after the print function outputs the content

  • The syntax format is as follows:

# After the output to the console is completed, there is no newline
print("*", end="")

# Simple line feed
print("")

end = "" indicates that the output to the console will not wrap

Suppose Python does not provide a * operation for string splicing

demand

  • Five consecutive lines * are output on the console, and the number of asterisks in each line increases in turn
*
**
***
****
*****

Development steps

  • 1> Complete a simple output of 5 lines
  • 2> How to deal with the * inside each line?
    • The number of stars displayed in each row is consistent with the current number of rows
    • A small loop is nested to deal with the star display of columns in each row
row = 1

while row <= 5:

    # Suppose python does not provide a string * operation
    # Inside the loop, another loop is added to realize the star printing of each line
    col = 1

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

        col += 1

    # After the asterisk of each line is output, add a new line
    print("")

    row += 1

Step 3: 99 multiplication table

Demand output 99 multiplication table, the format is as follows:

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 lines of small stars
*
**
***
****
*****
******
*******
********
*********
    1. Replace each * with the corresponding row and column multiplication
# Define start line
row = 1

# Maximum print 9 lines
while row <= 9:
    # Define start column
    col = 1

    # Maximum print row column
    while col <= row:

        # end = "" indicates that there is no newline after the output
        # "\ t" can output a tab on the console to assist alignment when outputting text
        print("%d * %d = %d" % (col, row, row * col), end="\t")

        # Number of columns + 1
        col += 1

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

    # Number of rows + 1
    row += 1

Escape character in string

  • \Tput a tab on the console to help maintain vertical alignment when outputting text
  • \n outputs a newline character on the console

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

Escape characterdescribe
\\Backslash symbol
\'Single quotation mark
\"Double quotation mark
\nLine feed
\thorizontal tab
\renter

Reference video: dark horse programmer Python

Tags: Python

Posted on Thu, 21 Oct 2021 15:59:37 -0400 by bladechob