×
Python 基础教程Python 简介Python 环境搭建Python 中文编码Python 基础语法Python 变量类型Python 运算符Python 条件语句Python 循环语句Python While循环语句Python for 循环语句Python 循环嵌套Python break 语句Python continue 语句Python pass 语句Python 数字Python 字符串Python 列表(Lists)Python 元组Python 字典(Dictionary)Python 日期和时间Python 函数Python 模块Python 文件I/OPython File(文件) 方法Python 异常处理Python OS 文件/目录方法Python 内置函数

Python 高级教程

Python 面向对象Python 正则表达式Python CGI编程python MysqlPython SMTPPython 多线程Python XML解析python GUI编程(Tkinter)Python 2.x与3​​.x版本区别Python IDEPython JSONPython 100例

Python 循环嵌套


Python 语言允许在一个循环体里面嵌入另一个循环。

Python for 循环嵌套语法:


for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python while 循环嵌套语法:


while expression:
   while expression:
      statement(s)
   statement(s)

你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。

实例:

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


#coding=utf-8
#!/usr/bin/python

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!"

以上实例输出结果:


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!

分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)