首先来看c/c++语言,在c/c++中我们在处理一个循环时,通常是如下形式
for(i=0;i<n;i++)
{your code}//可能有必要的break或者continue语句
或者
while(True)
{your code}//可能有必要的break或者continue语句
基本上是for/while关键字加上条件,然后循环体内写代码,代码内可能包含了必要的break或者continue语句来跳出循环或者跳过当此循环。而循环之后再则是其他语句,与前边的循环无直接关系
我们再来看python语言,在Python中的while或者for循环之后还可以有else子句,形如下:
for x in range(1,5): if x == 6 : print "found the number",x break; else: print "not found!"
保存上边的代码,运行得到“not found”,WHY?我们先来看看python官方文档中的解释,原文在这儿:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
翻译:循环语句后可以有一个else从句,这个else从句在因为for循环中list全部遍历完或者因为while循环中条件不满足而执行,而如果循环中有break语句执行了则else从句就不执行了。。
简单理解来:for循环中if条件一直不满足,则最后就执行else语句
我们这里来简单想象下如果用c语言式的写法,即添加found flag
found = false for x in range(1,5): if x == 6: found = True print "found the number",x break; if !found: print "nout found!"
每个人有可能对这样的实现有自己的理解,可能大家更喜欢或者习惯使用found flag:)
更多的讨论,在这里
发表在《
发表在《
发表在《
发表评论的名字下面的日期有点蛋疼哦。。。重复了?
[回复]
C语言学习中,python放在后面的
[回复]
freetstar
回复:
十一月 2nd, 2011 at 6:12 下午
python比c好学,哈哈
[回复]
看懂了什么意思,嗯,不过我还没用过python就是了~
[回复]
freetstar
回复:
十月 29th, 2011 at 7:43 下午
@婉秋, 还是你懂~
[回复]
用来说明文章核心意思的例子中的else缩进有问题
[回复]
freetstar
回复:
十月 28th, 2011 at 10:05 上午
@yish, 恩恩,已修正,thx
[回复]
其实也不是很必要的说
[回复]
freetstar
回复:
十月 28th, 2011 at 10:03 上午
@Mucid, 其实也是为了易读性,还有在try/except后还可以跟上else子句
[回复]
else应该跟for对齐,
按文中的缩进格式, 应该输出4个not found
[回复]
freetstar
回复:
十月 28th, 2011 at 10:04 上午
@hitsmaxft, 感谢,已修正
[回复]
last 和 next 伤不起啊!
[回复]
freetstar
回复:
十月 27th, 2011 at 6:23 下午
@Tao Zhu, 啥意思。。
[回复]
Tao Zhu
回复:
十月 27th, 2011 at 6:24 下午
@freetstar, 去翻翻 Perl 的书就 OK
[回复]
freetstar
回复:
十月 27th, 2011 at 6:25 下午
@Tao Zhu, 呃。。明白了
[回复]