Python novice tutorial 4, loop statement

4.1 for loop statement

The for loop is more suitable for a fixed number of loops. When using for loop statements, you need to pay attention to the statements you want to loop need to be indented.

for i in range(循环次数):
    循环内容

For example, the following code

for i in range(5):
    monkey.move(10)

The effect he achieved was to make the monkey on the stage move 10 steps at a time, 5 times in total, for a total of 50 steps. In other words, he moves 10 steps in 5 cycles.

4.2 while loop statement

The while loop is more suitable for conditional loops. When we don't know the number of loops, but only know under what conditions to start the loop, we can use the while loop statement.

When using the while loop, pay attention to the conditions you fill in. In the process of our loop, we must modify the relevant variables in the loop. For example, the following code:

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

In this code, we create a count variable to store the number of loops, and initialize it to 0, and then use the while loop statement, when the value of count is less than 5, the loop is executed. In the loop, print the value of the count variable, and then increase the value of count by one. When the value of count is no longer less than 5, there is no longer a loop.

If you forget to modify the condition in the loop, that is, when there is no code of count += 1, the value of count will always be 0, that is, it will always be less than 5, and this loop will become an infinite loop.

Code format:

while 条件:
    循环内容
    修改条件变量

Let's take a look at an example of a while loop. In the following code, the effect we achieve is that the monkey moves 10 steps at a time, for a total of 50 steps. That is to loop 5 times, the code using [while loop] is like this, the condition is that the value of count is less than 5.

count = 0
while count < 5:
    monkey.move(10)
    count += 1

If we forget to modify the value of count in the loop, the value of count will always be 0, and the condition of count <5 will always be true, and this while loop becomes an infinite loop. That is the following piece of code:

# 条件为true,循环就会一直持续
import time
while True:
    monkey.move(10)
    time.sleep(1)

Note, we occasionally need to use [Infinite Loop] in programming. At this time, we can directly use [while True] to achieve the effect of infinite loop.

4.3 Small test

Please use [for loop statement] and [while loop statement] to write the code, each time the monkey advances 5 steps, repeat this operation 10 times.

The correct answer will be announced in the next issue

Answer from the previous issue: C

Guess you like

Origin blog.csdn.net/m0_52519239/article/details/113091993