Python learning notes 11: Python loop statements

target

  • Understanding loops
  • while syntax [key]
  • while application
  • break and continue
  • while loop nesting [ key ]
  • while loop nesting application [difficulty]
  • for loop

I Cycle introduction

1.1 function of circulation

Thinking: if I have a girlfriend, one day we are angry with each other. The girlfriend says: apologize and say "daughter-in-law, I'm wrong" 100 times. What will programmers do at this time?

A: 100 times print('daughter-in-law, I'm wrong ')

Think: copy and paste 100 times?

A: repeat the same code for 100 times and cycle in the program

The function of loop: make the code execute repeatedly more efficiently.

1.2 classification of cycles

In Python, loops are divided into while and for, and the final implementation effect is the same.

II Syntax of while

while condition:
    Code 1 repeatedly executed when the condition is true
    Code 2 executed repeatedly when the condition is true
    ......

2.1 quick experience

Requirement: repeat the print for 100 times ('daughter-in-law, I'm wrong ') (the output is more concise. We set it here for 5 times).

Analysis: the initial value is 0 times and the end point is 5 times. The repeated things output "daughter-in-law, I'm wrong".

# Cyclic counter
i = 0
while i < 5:
    print('Daughter in law, I was wrong')
    i += 1

print('End of task')

III Application of while

3.1 application I: calculate 1-100 cumulative sum

Analysis: cumulative sum of 1-100, i.e. 1 + 2 + 3 + 4 +, That is, the addition result of the first two numbers + the next number (the previous number + 1).

i = 1
result = 0
while i <= 100:
    result += i
    i += 1

# Output 5050
print(result)

Note: in order to verify the accuracy of the program, you can change the small value first, and then change it to 1-100 for accumulation after the verification result is correct.

3.2 application 2: calculate 1-100 even cumulative sum

Analysis: the even sum of 1-100, i.e. 2 + 4 + 6 + 8... Is obtained as follows:

  • An even number is a number with the remainder of and 2 as 0. You can add a conditional statement to judge whether it is an even number. If it is an even number, it will be accumulated
  • The initial value is 0 / 2, and the counter accumulates 2 each time

3.2. 1 method 1: condition judgment and 2 remainder are accumulated

# Method 1: condition judgment and 2. If the remainder is 0, it will be accumulated
i = 1
result = 0
while i <= 100:
    if i % 2 == 0:
        result += i
    i += 1

# Output 2550
print(result)

3.2. 2 method 2: counter control

# Method 2: the counter control increment is 2
i = 0
result = 0
while i <= 100:
    result += i
    i += 2

# Output 2550
print(result)

4, break and continue

break and continue are two different ways to exit a loop when certain conditions are met.

4.1 understanding

For example: eat a total of 5 apples. After eating the first, eat the second... Is the action of "eating apples" repeated here?

Case 1: if you are full after eating the third apple, you do not need to eat the fourth and fifth apples, that is, the action of eating apples stops. Here is the break control cycle process, that is, terminate the cycle.

Case 2: if you eat the third apple and eat a big bug... Do you stop eating the apple and start eating the fourth apple? Here is the continue control loop process, that is, exit the current loop and then execute the next loop code.

4.1. 1 case 1: break

i = 1
while i <= 5:
    if i == 4:
        print(f'Don't eat when you're full')
        break
    print(f'Eat the second{i}An apple')
    i += 1

4.1. 2. Case 2: continue

i = 1
while i <= 5:
    if i == 3:
        print(f'Big bug, No{i}I don't eat anymore')
        # Be sure to modify the counter before continue, otherwise it will fall into an endless loop
        i += 1
        continue
    print(f'Eat the second{i}An apple')
    i += 1

Execution results:

V while loop nesting

5.1 application scenarios

Synopsis of the story: one day, my girlfriend was angry again. Punishment: say "daughter-in-law, I'm wrong" three times. Is this procedure a cycle? But if your girlfriend says: I have to brush today's dinner bowl, how does this program write?

while condition:
    print('Daughter in law, I was wrong')
print('Brush the dinner bowl')

But if the girlfriend is still angry and the punishment should be implemented for three consecutive days, how to write the procedure?

while condition:
    while condition:
        print('Daughter in law, I was wrong')
    print('Brush the dinner bowl')

5.2 syntax

while Condition 1:
    Code executed when condition 1 is true
    ......
    while Condition 2:
        Code executed when condition 2 is true
        ......

Summary: the so-called while loop nesting means that a while is nested inside a while. Each while is the same as the previous basic syntax.

5.3 quick experience: reproducing scenes

5.3. 1 code

j = 0
while j < 3:
    i = 0
    while i < 3:
        print('Daughter in law, I was wrong')
        i += 1
    print('Brush the dinner bowl')
    print('A set of punishment ends----------------')
    j += 1

5.3. 2 execution results

5.3. 3 understand the execution process

After the execution of the internal loop is completed, the condition judgment of the next external loop is executed.

Vi Nested application of while loop

6.1 application 1: print asterisk (square)

6.1. 1 demand

*****
*****
*****
*****
*****

6.1. 2 code

Analysis: output 5 asterisks in one line and print 5 lines repeatedly

# Repeat printing 5 lines of stars
j = 0
while j <= 4:
    # Print a line of stars
    i = 0
    while i <= 4:
        # Stars in a line cannot wrap. Cancel the default end of print \ n
        print('*', end='')
        i += 1
    # At the end of each line, a new line is required. Here, with the help of an empty print, the default end character of print is used to wrap the line
    print()
    j += 1

6.2 application 2: print asterisk (triangle)

6.2. 1 demand

*
**
***
****
*****

6.2. 2 code

Analysis: the number of stars output in one line is equal to the line number. For each line: repeatedly print the line number and the number of stars. Repeat the command to print the planet number for 5 times to print 5 lines.

# Repeat printing 5 lines of stars
# j represents the line number
j = 0
while j <= 4:
    # Print a line of stars
    i = 0
    # i represents the number of stars in each row. This number should be equal to the row number, so i should be linked with j
    while i <= j:
        print('*', end='')
        i += 1
    print()
    j += 1

6.3 99 multiplication table

6.3. 1 execution results

6.3. 2 code

# Print 9 lines of expression repeatedly
j = 1
while j <= 9:
    # Print the expression a * b = a*b in one line
    i = 1
    while i <= j:
        print(f'{i}*{j}={j*i}', end='\t')
        i += 1
    print()
    j += 1

7, for loop

7.1 syntax

for Temporary variable in sequence:
    Repeated code 1
    Repeated code 2
    ......

7.2 quick experience

str1 = 'itheima'
for i in str1:
    print(i)

7.3 break

str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('encounter e Do not print')
        break
    print(i)

7.4 continue

str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('encounter e Do not print')
        continue
    print(i)

VIII else

Loops can be used with else. The indented code below else refers to the code to be executed after the loop ends normally.

8.1 while...else

Demand: if your girlfriend is angry, you should be punished: say "daughter-in-law, I'm wrong" five times in a row. If the apology is completed normally, your girlfriend will forgive me. How to write this program?

i = 1
while i <= 5:
    print('Daughter in law, I was wrong')
    i += 1
print('My daughter-in-law forgave me...')

Think: can this print be executed without a loop?

8.1. 1 Grammar

while condition:
    Code executed repeatedly when the condition is true
else:
    Code to be executed after the loop ends normally

8.1. 2 example

i = 1
while i <= 5:
    print('Daughter in law, I was wrong')
    i += 1
else:
    print('My daughter-in-law forgives me. I'm so happy, ha ha')

8.1. 3 way to exit the cycle

Demand: the girlfriend is angry and asks for an apology five times: daughter-in-law, I'm wrong. When she apologized for the third time, her daughter-in-law complained that she was not sincere. Is she going to quit the cycle? There are two possibilities for this exit:

  • More angry, do not intend to forgive, do not need to apologize, how to write the program?
  • Only one time is insincere and can be tolerated. Continue to apologize the next time. How to write the program?
  1. break
i = 1
while i <= 5:
    if i == 3:
        print('It's not sincere this time')
        break
    print('Daughter in law, I was wrong')
    i += 1
else:
    print('My daughter-in-law forgives me. I'm so happy, ha ha')

Else refers to the code to be executed after the normal end of the loop, that is, if the loop is terminated by break, the code indented below else will not be executed.

  1. continue
i = 1
while i <= 5:
    if i == 3:
        print('It's not sincere this time')
        i += 1
        continue
    print('Daughter in law, I was wrong')
    i += 1
else:
    print('My daughter-in-law forgives me. I'm so happy, ha ha')

Because continue is to exit the current cycle and continue the next cycle, the cycle can normally end under the control of continue. When the cycle ends, the else indented code is executed.

8.2 for...else

8.2. 1 Grammar

for Temporary variable in sequence:
    Repeatedly executed code
    ...
else:
    Code to be executed after the loop ends normally

Else refers to the code to be executed after the normal end of the loop, that is, if the loop is terminated by break, the code indented below else will not be executed.

8.2. 2 example

str1 = 'itheima'
for i in str1:
    print(i)
else:
    print('Code executed after the loop ends normally')

8.2. 3 way to exit the cycle

  1. break terminates the loop
str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('encounter e Do not print')
        break
    print(i)
else:
    print('Code executed after the loop ends normally')

No code to perform else indentation.

  1. continue control loop
str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('encounter e Do not print')
        continue
    print(i)
else:
    print('Code executed after the loop ends normally')

Because continue is to exit the current cycle and continue the next cycle, the cycle can normally end under the control of continue. When the cycle ends, the else indented code is executed.

summary

  • The function of loop: control the repeated execution of code
  • while syntax
while condition:
    Code 1 repeatedly executed when the condition is true
    Code 2 executed repeatedly when the condition is true
    ......
  • while loop nesting syntax
while Condition 1:
    Code executed when condition 1 is true
    ......
    while Condition 2:
        Code executed when condition 2 is true
        ......
  • for loop syntax
for Temporary variable in sequence:
    Repeated code 1
    Repeated code 2
    ......
  • break exits the entire loop
  • Continue exit this loop and continue to execute the next repeated code
  • else
    • Both while and for can be used with else
    • Meaning of the code indented below else: the code executed when the loop ends normally
    • Breaking the loop does not execute the code indented below else
    • continue executes the indented code below else by exiting the loop
print("If the article is useful to you, please like it O(∩_∩)O~")
System.out.println("If the article is useful to you, please like it O(∩_∩)O~");
cout<<"If the article is useful to you, please like it O(∩_∩)O~"<<endl;

Keywords: Python

Added by AngelG107 on Tue, 28 Dec 2021 21:25:04 +0200