Carambola Python Advanced Lecture 15-Loop (3) Multiple Loop

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

 

Practical example

In life we ​​know the clock well, 1 day = 24 hours, 1 hour = 60 minutes, 1 minute = 60 seconds

If we need to count from 1 second to 3 hours, then we must count from this:

1 second, 2 seconds, 3 seconds ... 59 seconds, 1 minute

1 minute 1 second, 1 minute 2 seconds ... 1 minute 59 seconds, 2 minutes

……

59 minutes 1 second, 59 minutes 2 seconds ... 59 minutes 59 seconds, 1 hour

……

2 hours 59 minutes 1 second, 2 hours 59 minutes 2 seconds ... 2 hours 59 minutes 59 seconds, 3 hours

It can be seen that when we are several minutes, we must first complete the count of 60 seconds. In a few hours, we must also finish counting the minutes.

Therefore, this constitutes a multi-loop , the outer loop must be executed first inner loop

 

Multiple loop code implementation

Note: In order to avoid a "dead loop" that can never end, it is necessary to add judgment conditions or self-increment assignment numbers to the variables in the loop body + =

for h in range(3):
  for m in range(60):
    for s in range(60):
      print("The time is %d:%d:%d" %(h,m,s))
      s += 1
    m += 1
  h += 1

运行结果:
The time is 0:0:0
The time is 0:0:1
The time is 0:0:2
...
The time is 0:0:58
The time is 0:0:59
The time is 0:1:0
The time is 0:1:1
...
The time is 0:1:58
The time is 0:1:59
The time is 0:2:0
The time is 0:2:1
...
The time is 0:59:58
The time is 0:59:59
The time is 1:0:0
The time is 1:0:1
...
The time is 1:59:58
The time is 1:59:59
The time is 2:0:0
The time is 2:0:1
...
The time is 2:59:58
The time is 2:59:59

***Repl Closed***

Because the number in Python's range () function is unavailable, the entire loop is terminated by 2:59:59.

Points to note for multiple cycles

(1) The indentation of the cyclic hierarchy should be correct

(2) Flexible use of range () function, the general format is as follows:

range([n], m, [s])

Note: n represents the starting number, if you omit the default, it will start traversing from 0.

           m represents the termination number, in fact it terminates after traversing to m-1. This parameter cannot be omitted.

           s represents the step size, that is, a few digits at a time and then traverse the next digit. The step size can be positive or negative.

           If omitted, the default step size is 1.

(3) If it is not necessary, it is not necessary to output the result of each loop, because the output result is much more CPU and memory than the execution of the loop.

 

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

If you think this chapter is helpful to you, welcome to follow, comment and like! Github welcomes your Follow and Star!

Published 55 original articles · won praise 16 · views 6111

Guess you like

Origin blog.csdn.net/yty_7/article/details/104664955