Article Directory
the goal
- Understanding the loop
- while syntax [emphasis]
- while application
- break和continue
- While loop nesting [emphasis]
- While loop nested application [difficulty]
- for loop
1. Introduction to Cycle
1.1 The role of circulation
Thinking: If I have a girlfriend, one day we are in conflict and 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('媳妇儿,我错了')
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 repeated execution.
1.2 Classification of cycles
In Python, the cycle is divided while
, and for
two kinds, ultimately to the same effect.
2. The syntax of while
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
......
2.1 Quick experience
Requirement: Repeat 100 times to reproduce print('媳妇儿,我错了')
(the output is more concise, we set 5 times here).
Analysis: The initial value is 0 times, and the end point is 5 times. If you repeat things, output "Daughter-in-law, I was wrong".
# 循环的计数器
i = 0
while i < 5:
print('媳妇儿,我错了')
i += 1
print('任务结束')
3. The application of while
3.1 Application 1: Calculate 1-100 cumulative sum
Analysis: The cumulative sum of 1-100, that is, 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
# 输出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 verifying the result is correct.
3.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 even numbers is as follows:
- An even number is a number whose remainder with 2 is 0. A conditional statement can be added to determine whether it is an even number. If it is an even number, it will be accumulated
- The initial value is 0/2, the counter accumulates by 2 each time
3.2.1 Method 1: Conditional judgment and accumulation of the remainder of 2
# 方法一:条件判断和2取余数为0则累加计算
i = 1
result = 0
while i <= 100:
if i % 2 == 0:
result += i
i += 1
# 输出2550
print(result)
3.2.2 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 when certain conditions are met in the loop.
4.1 Understanding
Example: A total of 5 apples are eaten, the first one is eaten, the second one is eaten..., is the action of "eating apple" repeated here?
Situation 1: If you are full after eating the third apple in the process of eating, you do not need to eat the fourth and fifth apples, that is, the action of eating apples is stopped, here is the break control cycle process, that isEnd this loop。
Situation 2: If in the process of eating, if you eat the third one and eat a big bug..., do you stop eating this apple and start eating the fourth apple, here is the continue control cycle process, that isExit the current loop and execute the next loop code。
4.1.1 Case 1: break
i = 1
while i <= 5:
if i == 4:
print(f'吃饱了不吃了')
break
print(f'吃了第{i}个苹果')
i += 1
Results of the:
4.1.2 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:
Five. While loop nesting
5.1 Application scenarios
Summary of the story: One day the girlfriend got angry again. Punishment: Say "Daughter-in-law, I was wrong" three times. Is this procedure just a loop? But if my girlfriend says: I still want to clean the bowl for dinner today, how do I write this program?
while 条件:
print('媳妇儿, 我错了')
print('刷晚饭的碗')
But if the girlfriend is still angry and has to execute this set of punishments for 3 consecutive days, how to write the procedure?
while 条件:
while 条件:
print('媳妇儿, 我错了')
print('刷晚饭的碗')
5.2 Syntax
while 条件1:
条件1成立执行的代码
......
while 条件2:
条件2成立执行的代码
......
Summary: The so-called while loop nesting is the writing of a while inside a while. Each while is the same as the previous basic syntax.
5.3 Quick Experience: Recover the scene
5.3.1 Code
j = 0
while j < 3:
i = 0
while i < 3:
print('媳妇儿,我错了')
i += 1
print('刷晚饭的碗')
print('一套惩罚结束----------------')
j += 1
5.3.2 Execution results
5.3.3 Understanding the execution process
After the execution of the inner loop is completed, the condition judgment of the next outer loop is executed.
Six. While loop nested application
6.1 Application 1: Print asterisk (square)
6.1.1 Requirements
*****
*****
*****
*****
*****
6.1.2 Code
Analysis: output 5 asterisks in one line, and 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
6.2 Application 2: Print asterisk (triangle)
6.2.1 Requirements
*
**
***
****
*****
6.2.2 Code
analysis:The number of stars and the line number in a line of output are equal, Each line: repeat the print line number digits and asterisks, repeat the command to print the planet 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
6.3 Nine-Nine Multiplication Table
6.3.1 Execution results
6.3.2 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
Seven, for loop
7.1 Syntax
for 临时变量 in 序列:
重复执行的代码1
重复执行的代码2
......
7.2 Quick experience
str1 = 'hello'
for i in str1:
print(i)
Results of the:
7.3 break
str1 = 'helloworld'
for i in str1:
if i == 'w':
print('遇到w不打印')
break
print(i)
Results of the:
7.4 continue
str1 = 'helloworld'
for i in str1:
if i == 'w':
print('遇到w不打印')
continue
print(i)
Results of the:
八. else
Loop can be used in conjunction with else, the indented code below else refers toThe code to be executed when the loop ends normally。
8.1 while…else
Requirement: My girlfriend is angry and should be punished: Say "daughter-in-law, I was wrong" 5 times in a row. If the apology is completed normally, the 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?
8.1.1 Syntax
while 条件:
条件成立重复执行的代码
else:
循环正常结束之后要执行的代码
8.1.2 Example
i = 1
while i <= 5:
print('媳妇儿,我错了')
i += 1
else:
print('媳妇原谅我了,真开心,哈哈哈哈')
8.1.3 Ways to exit the loop
Demand: My girlfriend is angry and asks for an apology 5 times: Wife, I was wrong. When the apology came to the third time, the daughter-in-law complained that she was insincere this time, did she just want to get out of the loop? There are two possibilities for this withdrawal:
- I'm even more angry. I don't intend to forgive, and I don't need to apologize. How to write the program?
- Only once insincere, can bear it, continue to apologize again, how to write the program?
- break
i = 1
while i <= 5:
if i == 3:
print('这遍说的不真诚')
break
print('媳妇儿,我错了')
i += 1
else:
print('媳妇原谅我了,真开心,哈哈哈哈')
The so-called else refers to the code to be executed after the loop ends normally, that is, if the break terminates the loop, 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('媳妇原谅我了,真开心,哈哈哈哈')
Because continue is to exit the current loop and continue to the next loop, the loop can end normally under the control of continue. When the loop ends, the code of the else indentation is executed.
8.2 for…else
8.2.1 Syntax
for 临时变量 in 序列:
重复执行的代码
...
else:
循环正常结束之后要执行的代码
The so-called else refers to the code to be executed after the loop ends normally, that is, if the break terminates the loop, the indented code below the else will not be executed.
8.2.2 Example
str1 = 'helloworld'
for i in str1:
print(i)
else:
print('循环正常结束之后执行的代码')
8.2.3 Ways to exit the loop
- break to terminate the loop
str1 = 'helloworld'
for i in str1:
if i == 'w':
print('遇到w不打印')
break
print(i)
else:
print('循环正常结束之后执行的代码')
Results of the:
There is no code to perform the else indentation.
- continue control loop
str1 = 'helloworld'
for i in str1:
if i == 'w':
print('遇到w不打印')
continue
print(i)
else:
print('循环正常结束之后执行的代码')
Results of the:
Because continue is to exit the current loop and continue to the next loop, the loop can end normally under the control of continue. When the loop ends, the code of the else indentation is executed.
to sum up
- The role of the loop: control code repeated execution
- while syntax
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
......
- While loop nested syntax
while 条件1:
条件1成立执行的代码
......
while 条件2:
条件2成立执行的代码
......
- for loop syntax
for 临时变量 in 序列:
重复执行的代码1
重复执行的代码2
......
- break to exit the entire loop
- continue to exit this loop and continue to execute the next repeated code
- else
- Both while and for can be used with else
- The meaning of the code indented under the else: the code executed when the loop ends normally
- break to terminate the loop will not execute the indented code below else
- continue to exit the loop to execute the indented code below else
The content of this section is over, please pay attention, don’t get lost