Explain the python loop statement through the case

1. Introduction to cycle

1. The role of circulation

Thinking: If I have a girlfriend, one day we have conflicts and get angry, and the girlfriend says: Apologize, and say "Daughter-in-law, I was wrong" 100 times. What will the programmer do at this time?

Answer: 100 times print('Daughter-in-law, I was wrong')

Thinking: copy and paste 100 times?

Answer: Repeat the same code 100 times, just loop in the program

The role of the loop: to make the code more efficient and repeated execution.

2 Classification of cycles

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

2. The syntax of while

while 条件:
    条件成立重复执行的代码1
    条件成立重复执行的代码2
    ......

1 Quick experience

Requirements: Repeat print('Daughter-in-law, I was wrong') 100 times (the output is more concise, we set it 5 times here).

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

# 循环的计数器
i = 0
while i < 5:
    print('媳妇儿,我错了')
    i += 1

print('任务结束')

3. The application of while

1 Application 1: Calculating the cumulative sum of 1-100

Analysis: The cumulative sum of 1-100, that is, 1 + 2 + 3 + 4 +…., that is, the result of the addition of the previous two numbers + the next number (previous number + 1).

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

# 输出5050
print(result)

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

2 Application 2: Calculate the cumulative sum of 1-100 even numbers

Analysis: The sum of even numbers from 1-100, that is, 2 + 4 + 6 + 8..., the method to get an even number is as follows:

  • An even number is a number whose remainder is 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 increments by 2 each time

Method 1: Conditional judgment and 2 to take the remainder and accumulate

# 方法一:条件判断和2取余数为0则累加计算
i = 1
result = 0
while i <= 100:
    if i % 2 == 0:
        result += i
    i += 1

# 输出2550
print(result)

Method 2: Counter Control

# 方法二:计数器控制增量为2
i = 0
result = 0
while i <= 100:
    result += i
    i += 2

# 输出2550
print(result)

Four, break and continue

break and continue are two different ways to exit the loop if certain conditions are met in the loop.

understand

Example: eat a total of 5 apples, eat the first one, eat the second..., is the action of "eating apples" repeated here?

Situation 1: If you are full after eating the third apple during the eating process, you don’t need to eat the fourth and fifth apples, that is, the action of eating apples stops. Here is the break control loop process, that is, terminate this cycle.

Situation 2: If in the process of eating, a big bug comes out after eating the third one..., is it possible that this apple will not be eaten, and the fourth apple will be eaten, here is the continue control loop process, that is, exit the current cycle and continue Execute the next loop code.

Case 1: break

i = 1
while i <= 5:
    if i == 4:
        print(f'吃饱了不吃了')
        break
    print(f'吃了第{
      
      i}个苹果')
    i += 1

Results of the:

吃了第1个苹果
吃了第2个苹果
吃了第3个苹果
吃饱了不吃了

Case 2: continue

i = 1
while i <= 5:
    if i == 3:
        print(f'大虫子,第{
      
      i}个不吃了')
        # 在continue之前一定要修改计数器,否则会陷入死循环
        i += 1
        continue
    print(f'吃了第{
      
      i}个苹果')
    i += 1

Results of the:

吃了第1个苹果
吃了第2个苹果
大虫子,第3个不吃了
吃了第4个苹果
吃了第5个苹果

Five. While loop nesting

1 Application Scenarios

Summary of the story: One day the girlfriend got angry again, the punishment: say "Daughter-in-law, I was wrong" 3 times, can this program just loop? But if the girlfriend says: I have to clean the dishes for dinner today, how to write this program?

while 条件:
    print('媳妇儿, 我错了')
print('刷晚饭的碗')

But if the girlfriend is still angry, and this set of punishment has to be carried out for 3 consecutive days, how to write the procedure?

while 条件:
    while 条件:
        print('媳妇儿, 我错了')
    print('刷晚饭的碗')

2 Grammar

while 条件1:
    条件1成立执行的代码
    ......
    while 条件2:
        条件2成立执行的代码
        ......

Summary: The so-called while loop nesting is the writing method of nesting a while inside a while. Each while is the same as the previous basic syntax.

3 Quick experience: reproduce the scene

the code

j = 0
while j < 3:
    i = 0
    while i < 3:
        print('媳妇儿,我错了')
        i += 1
    print('刷晚饭的碗')
    print('一套惩罚结束----------------')
    j += 1

Results of the

媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
刷晚饭的碗
一套惩罚结束----------------
媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
刷晚饭的碗
一套惩罚结束----------------
媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
刷晚饭的碗
一套惩罚结束----------------

Understand the execution flow

After the execution of the inner loop is completed, the conditional judgment of the next outer loop is executed.
insert image description here

6. While loop nested application

1 Application 1: Print asterisks (squares)

need

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

the code

Analysis: Output 5 asterisks in one line, print 5 lines repeatedly

# 重复打印5行星星
j = 0
while j <= 4:
    # 一行星星的打印
    i = 0
    while i <= 4:
        # 一行内的星星不能换行,取消print默认结束符\n
        print('*', end='')
        i += 1
    # 每行结束要换行,这里借助一个空的print,利用print默认结束符换行
    print()
    j += 1
2 Application 2: Print asterisks (triangles)

need

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

the code

Analysis: The number of stars output in one line is equal to the line number, each line: repeatedly print the number of asterisks of the line number, repeat the command to print the star number 5 times to print 5 lines.

# 重复打印5行星星
# j表示行号
j = 0
while j <= 4:
    # 一行星星的打印
    i = 0
    # i表示每行里面星星的个数,这个数字要和行号相等所以i要和j联动
    while i <= j:
        print('*', end='')
        i += 1
    print()
    j += 1

3 ninety-nine multiplication table

the code

# 重复打印9行表达式
j = 1
while j <= 9:
    # 打印一行里面的表达式 a * b = a*b
    i = 1
    while i <= j:
        print(f'{
      
      i}*{
      
      j}={
      
      j*i}', end='\t')
        i += 1
    print()
    j += 1

Results of the

insert image description here

Seven, for loop

1 Grammar

for 临时变量 in 序列:
    重复执行的代码1
    重复执行的代码2
    ......

2 Quick experience

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

Results of the:

i
t
h
e
i
m
a

3 break

str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('遇到e不打印')
        break
    print(i)

Results of the:

i
t
h
遇到e不打印

4 continue

str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('遇到e不打印')
        continue
    print(i)

Results of the:

i
t
h
遇到e不打印
i
m
a

Eight. else

Loops can be used in conjunction with else, and the code indented below the else refers to the code to be executed after the loop ends normally.

1 while…else

Requirements: My girlfriend is angry and needs to be punished: say "Daughter-in-law, I was wrong" 5 times in a row, and if the apology is completed normally, my girlfriend will forgive me. How to write this program?

i = 1
while i <= 5:
    print('媳妇儿,我错了')
    i += 1
print('媳妇儿原谅我了...')

Thinking: Can this print be executed without a loop?

grammar

while 条件:
    条件成立重复执行的代码
else:
    循环正常结束之后要执行的代码

example

i = 1
while i <= 5:
    print('媳妇儿,我错了')
    i += 1
else:
    print('媳妇原谅我了,真开心,哈哈哈哈')

Results of the:

媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
媳妇儿,我错了
媳妇原谅我了,真开心,哈哈哈哈

way out of the loop

Requirement: Girlfriend is angry and asks to apologize 5 times: Wife, I was wrong. When the apology reaches the third time, the daughter-in-law complains that the insincerity of what she said this time is to quit the cycle? There are two possibilities for this exit:

  • Even more angry, I don't intend to forgive, and I don't need to apologize. How to write the program?
  • Only one insincere, tolerable, continue to apologize again, how to write the procedure?

break

i = 1
while i <= 5:
    if i == 3:
        print('这遍说的不真诚')
        break
    print('媳妇儿,我错了')
    i += 1
else:
    print('媳妇原谅我了,真开心,哈哈哈哈')

Results of the:

媳妇儿,我错了
媳妇儿,我错了
这遍说的不真诚

The so-called else refers to the code to be executed after the loop ends normally, that is, if the loop is terminated by a break, the indented code below the else will not be executed.

continue

i = 1
while i <= 5:
    if i == 3:
        print('这遍说的不真诚')
        i += 1
        continue
    print('媳妇儿,我错了')
    i += 1
else:
    print('媳妇原谅我了,真开心,哈哈哈哈')

Results of the:

媳妇儿,我错了
媳妇儿,我错了
这遍说的不真诚
媳妇儿,我错了
媳妇儿,我错了
媳妇原谅我了,真开心,哈哈哈哈
因为continue是退出当前一次循环,继续下一次循环,所以该循环在continue控制下是可以正常结束的,当循环结束后,则执行了else缩进的代码。

2 for…else

grammar

for 临时变量 in 序列:
    重复执行的代码
    ...
else:
    循环正常结束之后要执行的代码

The so-called else refers to the code to be executed after the loop ends normally, that is, if the loop is terminated by a break, the indented code below the else will not be executed.

example

str1 = 'itheima'
for i in str1:
    print(i)
else:
    print('循环正常结束之后执行的代码')

way out of the loop

break terminates the loop

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('遇到e不打印')
        break
    print(i)
else:
    print('循环正常结束之后执行的代码')

Results of the:

i
t
h
遇到e不打印

Code that does not perform else indentation.

continue control loop

str1 = 'itheima'
for i in str1:
    if i == 'e':
        print('遇到e不打印')
        continue
    print(i)
else:
    print('循环正常结束之后执行的代码')

Results of the:

i
t
h
遇到e不打印
i
m
a
循环正常结束之后执行的代码

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

Summarize

The function of the loop: the control code repeatedly executes
the while syntax

while 条件:
    条件成立重复执行的代码1
    条件成立重复执行的代码2
    ......

while loop nested syntax

while 条件1:
    条件1成立执行的代码
    ......
    while 条件2:
        条件2成立执行的代码
        ......

for loop syntax

for 临时变量 in 序列:
    重复执行的代码1
    重复执行的代码2
    ......

break exits the entire loop
continue exits this loop and continues to execute the next repeated code
else

  • Both while and for can be used with else
  • The meaning of the indented code below else: the code executed after the loop ends normally
  • break terminates the loop without executing the indented code below else
  • The way continue exits the loop executes the indented code below else

Guess you like

Origin blog.csdn.net/Python_222/article/details/129369929