Let you fully understand [python loop statement]

It is a headache to thoroughly figure out the loop statement in python, and I am no exception. After repeated use, it will be handy. This article explores the loop statement in python with you, so that you can say goodbye to the troubles of being troubled by loops.
  
insert image description here

  

1. for loop

  
The for loop is used to traverse all elements in a container object, and the loop statement segment will be executed once for each element of the container object.
  
  

1 basic syntax of for loop

  
The basic syntax rules of the for loop are as follows:

for var in sequence:
   statements(s)

That is, one element (var) is sequentially taken out from the sequence (sequence), and the statements (statements) in the code block are executed, usually the statement is related to the element. For a clearer understanding, let's look at a few different examples.
  
  

2 for loop instance 1

  
Let's first look at an example of outputting and printing food.

sequence = ['橙子', '榴莲', '草莓', '蓝莓', '西柚', '葡萄', '西瓜']
i = 1
for var in sequence:
    print(i)
    print('今天晚上吃什么?今天晚上吃', var,  '。', sep='')
    i += 1

The running logic of the code is: take out the variables from the sequence in turn, and run the code blocks in the loop statement. The code block first prints the value of i, then prints the second print statement, and finally increments the value of i by 1.
  
got the answer:

1
今天晚上吃什么?今天晚上吃橙子。
2
今天晚上吃什么?今天晚上吃榴莲。
3
今天晚上吃什么?今天晚上吃草莓。
4
今天晚上吃什么?今天晚上吃蓝莓。
5
今天晚上吃什么?今天晚上吃西柚。
6
今天晚上吃什么?今天晚上吃葡萄。
7
今天晚上吃什么?今天晚上吃西瓜。

  

3 for loop example 2

  
The for loop is often used in combination with the range function. The common usage of range is as follows:

range(num): 0 到 num-1 默认步长为1
range(start_num, end_num): start_num 到 end_num-1 默认步长为1
range(start_num, end_num, step): start_num 到 end_num-1 step(步长)

For a clearer understanding, let's look at a few examples.

for i in range(10):
    print('英文外刊阅读打卡第%d天'%(i))

got the answer:

英文外刊阅读打卡第0天
英文外刊阅读打卡第1天
英文外刊阅读打卡第2天
英文外刊阅读打卡第3天
英文外刊阅读打卡第4天
英文外刊阅读打卡第5天
英文外刊阅读打卡第6天
英文外刊阅读打卡第7天
英文外刊阅读打卡第8天
英文外刊阅读打卡第9天
可以发现range(10)默认从09步长为1

Generally, the reading check-in starts from the first day, and you only need to adjust the range function as follows:

for i in range(1, 10):
    print('英文外刊阅读打卡第%d天'%(i))

got the answer:

英文外刊阅读打卡第1天
英文外刊阅读打卡第2天
英文外刊阅读打卡第3天
英文外刊阅读打卡第4天
英文外刊阅读打卡第5天
英文外刊阅读打卡第6天
英文外刊阅读打卡第7天
英文外刊阅读打卡第8天
英文外刊阅读打卡第9

If you want to design the range function as an arithmetic sequence with a tolerance greater than 1, you only need to add a third parameter to range.
  
  

4 for loop example 3

  
The for loop can also be used with the else function, as follows:

for i in range(1, 10):
    print('英文外刊阅读打卡第%d天'%(i))
else:
    print('今天休息')

got the answer:

英文外刊阅读打卡第1天
英文外刊阅读打卡第2天
英文外刊阅读打卡第3天
英文外刊阅读打卡第4天
英文外刊阅读打卡第5天
英文外刊阅读打卡第6天
英文外刊阅读打卡第7天
英文外刊阅读打卡第8天
英文外刊阅读打卡第9天
今天休息

From the results, it can be found that else is a statement that runs after all loops have run.

  
  

Two, while loop

A while loop is similar to a for loop in that the statements in the body of the loop are executed while the condition is true. Let's look at a very simple example, when i is less than 5, execute the statements in the loop body.

i = 0
while i<5:
    print(i)
    i = i +1

got the answer:

0
1
2
3
4

  
  

3. Use of break and continue statements

Python loop statements are often used in conjunction with break and continue statements. The break statement means to end this loop, and the continue statement means to jump out of this loop and enter the next loop. Next, a group game is used to illustrate the use of break and continue statements. One such game can be played at a team dinner. The first person randomly reports a number within 20, and the following people report the number in turn according to the number reported by the first person. If you encounter a multiple of 7 or a number with 7 at the end, you should pat the table or clap your hands, and the rest of the numbers will be reported normally. If a mistake is made, the show is performed and the game starts over.
  
Next, let's look at the python simulation statement combined with the break statement.

import random

num = random.randint(1,20)
while True:
    if num>40:
        break
    elif num%7==0 or str(num)[-1] == '7':
        print('拍桌子或拍手')
    else:
        print(num)
    num = num +1

This statement refers to randomly generating an integer between 1 and 20. If the number is a multiple of 7 or the last number is 7, the output is to slap the table or clap hands. End the loop when the number is greater than 40, otherwise output the number.
  
got the answer:

19
20
拍桌子或拍手
22
23
24
25
26
拍桌子或拍手
拍桌子或拍手
29
30
31
32
33
34
拍桌子或拍手
36
拍桌子或拍手
38
39
40

Finally, let's look at the python simulation statement combined with the continue statement.

import random

num = random.randint(1,20)
while num<=40:
    if num==30:
        num += 1
        continue        
    elif num%7==0 or str(num)[-1] == '7':
        print('拍桌子或拍手')
    else:
        print(num)
    num = num +1

Since the break statement is not used, the while loop is not set as an infinite loop, and the loop is performed when num is less than 40. Only when num is equal to 30, jump out of this loop and enter the next loop.
  
got the answer:

11
12
13
拍桌子或拍手
15
16
拍桌子或拍手
18
19
20
拍桌子或拍手
22
23
24
25
26
拍桌子或拍手
拍桌子或拍手
29
31
32
33
34
拍桌子或拍手
36
拍桌子或拍手
38
39
40

From the results, it can be found that when num is equal to 30, neither the number is printed nor the table or hand is output. That is, jump out of this cycle and enter the next cycle.
  
So far, the loop statement in python has been explained, and interested friends can follow this article to implement it by themselves.
  
You may be interested in:
Draw Pikachu with PythonUse
Python to draw word cloudsPython
face recognition - only you in my eyesPython
draws beautiful starry sky (beautiful background)
[Python] Valentine's Day Confession Fireworks (with voice and text
) The py2neo library in Python operates neo4j to build a relationship map
Python romantic confession source code collection (love, rose, photo wall, confession under the stars)

Long press (scan) to recognize the QR code above to learn more Python and modeling knowledge, making your study and work more brilliant.

Guess you like

Origin blog.csdn.net/qq_32532663/article/details/121439669