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!'
本文详细介绍了Python中for循环的基本用法及其控制结构,包括如何使用break和continue来控制循环流程。通过一个具体的水果列表示例展示了如何在实际编程场景中应用这些概念。

被折叠的 条评论
为什么被折叠?



