首页 > 技术文章 > Python for else 循环控制

wangwp 2015-06-02 22:54 原文

for语句可用来遍历某一对象,还具有一个可选的else块。
如果for循环未被break终止,则执行else块中的语句。
break 在需要时终止for循环
continue 跳过位于其后的语句,开始下一轮循环。
for语句的格式如下:

for <> in <对象集合>if <条件>:
        break
    if <条件>:
        continue
    <其他语句>
else:
    <>

示例

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'

 

推荐阅读