0

5.8Python 循环中的else字句

Posted by 撒得一地 on 2016年4月11日 in python教程

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

简单的说,可以在for循环或while循环中增加一个else子句,但它仅在没有调用break时执行。

实例(win平台下),while循环中使用else字句,循环输出1到3,在循环结束后,输出"loop end!"提示:

>>> x = 0
>>> while x<=3:
...     x += 1
...     print(x)
... else :
...     print("loop end!")
...
1
2
3
loop end!

实例(win平台下),for循环中使用else字句,循环输出1到3,在循环结束后,输出"loop end!"提示:

>>> x = [1,2,3]
>>> y = 1
>>> for y in x:
...     print(y)
...     y+=1
... else:
...     print("loop end!")
...
1
2
3
loop end!

实例(Linux平台下),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

实例(Linux平台下),for循环使用else字句:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for letter in 'Python':     # 第一个实例
   print '当前字母 :', letter
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前字母 :', fruit

print "Good bye!"

以上实例输出结果:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前字母 : banana
当前字母 : apple
当前字母 : mango
Good bye!

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

2 + 6 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.