在Python的while循环中使用else以及循环嵌套的用法

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

在Python的while循环中使⽤else以及循环嵌套的⽤法
循环使⽤ else 语句
在 python 中,for … else 表⽰这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执⾏完(即 for 不是通过 break 跳出⽽中断的)的情况下执⾏,while … else 也是⼀样。

#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
以上实例输出结果为:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
简单语句组
类似if语句的语法,如果你的while循环体中只有⼀条语句,你可以将该语句与while写在同⼀⾏中,如下所⽰:
#!/usr/bin/python
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"
注意:以上的⽆限循环你可以使⽤ CTRL+C 来中断循环。

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之间的素数:#!/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!"
以上实例输出结果:
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!。

相关文档
最新文档