签到成功

知道了

CNDBA社区CNDBA社区

Python 基础教程系列(十 一)--嵌套循环

2017-04-07 16:59 2285 0 转载 python开发
作者: Expect-乐

Python 语言允许在一个循环体里面嵌入另一个循环。http://www.cndba.cn/Expect-le/article/1849

Python for 循环嵌套语法:

http://www.cndba.cn/Expect-le/article/1849

for iterating_var in sequence:

   for iterating_var in sequence:

      statements(s)

   statements(s)

Python while 循环嵌套语法:http://www.cndba.cn/Expect-le/article/1849http://www.cndba.cn/Expect-le/article/1849

http://www.cndba.cn/Expect-le/article/1849

while expression:

   while expression:

      statement(s)

   statement(s)

你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。http://www.cndba.cn/Expect-le/article/1849

实例:

以下实例使用了嵌套循环输出2~100之间的素数:

http://www.cndba.cn/Expect-le/article/1849

#!/usr/bin/python

# -*- coding: UTF-8 -*-

 

i = 2

while(i < 100):

   j = 2

   while(j <= (i/j)):

      if not(i%j): break

      j = j + 1

   if (j > i/j) : print i, " 是素数"

   i = i + 1

 

print "Good bye!"

http://www.cndba.cn/Expect-le/article/1849

以上实例输出结果:

http://www.cndba.cn/Expect-le/article/1849
http://www.cndba.cn/Expect-le/article/1849

2 是素数

3 是素数

5 是素数

7 是素数

11 是素数

13 是素数

17 是素数

19 是素数

23 是素数

29 是素数

31 是素数

37 是素数

41 是素数

43 是素数

47 是素数

53 是素数

59 是素数

61 是素数

67 是素数

71 是素数

73 是素数

79 是素数

83 是素数

89 是素数

97 是素数

Good bye!

python 嵌套循环

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
Expect-乐

Expect-乐

关注

Without the continuous bitter cold, there can be no fragrant plum blossom

  • 336
    原创
  • 6
    翻译
  • 100
    转载
  • 41
    评论
  • 访问:1567330次
  • 积分:1957
  • 等级:核心会员
  • 排名:第4名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ