您的位置:首页 > 编程语言 > Python开发

Python for else 循环控制

2015-06-02 22:54 966 查看
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!'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: