杨桃的Python进阶讲座15——循环(三)多重循环

本人CSDN博客专栏:https://blog.csdn.net/yty_7

Github地址:https://github.com/yot777/

实际的例子

在生活中我们对时钟了如指掌,1天=24小时,1小时=60分,1分=60秒

如果需要我们从1秒数到3小时,那我们一定是从这样数的:

1秒、2秒、3秒……59秒、1分

1分1秒、1分2秒……1分59秒、2分

……

59分1秒、59分2秒……59分59秒、1小时

……

2小时59分1秒、2小时59分2秒……2小时59分59秒、3小时

可见,我们在数分钟的时候,都必须先完成60秒的数数。在数小时的时候,我们也必须先完成分钟的数数。

因此这就构成了一个多重循环,执行外层循环都必须首先执行内层循环

多重循环代码实现

注意:为了避免出现永远无法结束的"死循环",需要在循环体中对变量加入判断条件或自增赋值号 +=

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***

因为Python的range()函数里的数字是取不到的,因此执行到2:59:59就终止整个循环。

多重循环需要注意的地方

(1)循环的层次结构的缩进要正确

(2)灵活运用range()函数,一般格式如下:

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

注意:n表示起始数字,如果省略默认则从0开始遍历。

           m表示终止数字,事实上遍历到m-1就终止。这个参数不能省略。

           s表示步长,即每次间隔几个数字再遍历下一个数字。步长可正可负。

           如果省略则默认步长为1。

(3)如无必要,不必输出每次循环的结果,因为输出结果远远比执行循环更占CPU和内存。

本人CSDN博客专栏:https://blog.csdn.net/yty_7

Github地址:https://github.com/yot777/

如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!

发布了55 篇原创文章 · 获赞 16 · 访问量 6111

猜你喜欢

转载自blog.csdn.net/yty_7/article/details/104664955
今日推荐