我注意到以下代码在 Python 中是合法的。我的问题是为什么?有具体原因吗?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
else
这个词是一个非常糟糕的主意,他们不会再做这些了。
after:
。
else
子句仅在您的 while
条件变为 false 时执行。如果您 break
退出循环,或者如果引发异常,则不会执行。
考虑它的一种方法是作为关于条件的 if/else 构造:
if condition:
handle_true()
else:
handle_false()
类似于循环结构:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
一个例子可能是这样的:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
如果您正常退出块,则执行 else
子句,方法是遇到循环条件或从 try 块的底部掉下来。如果您 break
或 return
超出块或引发异常,则它不会执行。它不仅适用于 while 和 for 循环,还适用于 try 块。
您通常会在通常会提前退出循环的地方找到它,并且在循环结束时运行是一个意外/不寻常的场合。例如,如果您在一个列表中循环查找一个值:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
found_it=False
放在循环的开头多少次,然后在最后对 found_it
进行 if 检查
作为对 Is there a specific reason?
的回复,这里有一个有趣的应用:打破多层次的循环。
它是这样工作的:外部循环在最后有一个中断,所以它只会执行一次。但是,如果内部循环完成(没有找到除数),那么它会到达 else 语句并且永远不会到达外部 break。这样,内部循环中的中断将中断两个循环,而不仅仅是一个循环。
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
对于 while
和 for
循环,else
语句在最后执行,除非使用了 break
。
在大多数情况下,有更好的方法来做到这一点(将其包装到函数中或引发异常),但这很有效!
当 while 条件评估为 false 时执行 else 子句。
只要表达式为真,while 语句用于重复执行: while_stmt ::= "while" expression ":" suite ["else" ":" suite] 这会重复测试表达式,如果为真,则执行第一套房;如果表达式为假(可能是第一次测试),则执行 else 子句套件(如果存在)并终止循环。在第一个套件中执行的 break 语句终止循环而不执行 else 子句的套件。在第一个套件中执行的 continue 语句会跳过套件的其余部分并返回测试表达式。
我的答案将集中在我们何时可以使用 while/for-else。
乍一看,使用时似乎没有什么不同
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
和
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
因为 print 'ELSE'
语句似乎总是在两种情况下都执行(无论是在 while
循环完成还是未运行时)。
那么,只有语句 print 'ELSE'
不会被执行时不同。就是在 while
下的代码块内有一个break
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
如果不同于:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return
不在此类别中,因为它对上述两种情况具有相同的效果。
异常引发也不会造成差异,因为当它引发时,下一个将执行的代码在异常处理程序(块除外)中,else
子句中或while
子句之后的代码将不会被执行。
else 子句仅在 while 条件变为 false 时执行。
这里有些例子:
示例 1:最初条件为假,因此执行 else 子句。
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
输出:
this
示例 2:while 条件 i < 5
从未变为 false,因为 i == 3
中断了循环,因此 else-clause 未被执行。
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
输出:
0
1
2
3
示例 3:当 i
为 5
时,while-condition i < 5
变为 false,因此执行了 else-clause。
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
输出:
0
1
2
3
4
this
我知道这是个老问题,但是......
正如 Raymond Hettinger 所说,它应该被称为 while/no_break
而不是 while/else
。
如果您查看此代码段,我会很容易理解。
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
现在,我们可以将它与 else
交换,而不是在 while 循环之后检查条件并摆脱该检查。
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
我总是把它读作 while/no_break
来理解代码,这种语法对我来说更有意义。
当且仅当 while 循环不再满足其条件时(在您的示例中,当 n != 0
为 false 时),才会执行 else:
语句。
所以输出将是这样的:
5
4
3
2
1
what the...
return
或引发异常,则 else
部分也不会运行。
如果 while 循环没有中断,则执行 Else。
我有点喜欢用“跑步者”的比喻来思考它。
“else”就像越过终点线,与您是从赛道的起点还是终点开始无关。仅当您在两者之间的某个地方中断时,才不会执行“else”。
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
主要用例是使用这种中断嵌套循环,或者如果您只想在循环没有在某处中断的情况下运行某些语句(认为中断是一种不寻常的情况)。
例如,以下是关于如何在不使用变量或 try/catch 的情况下跳出内部循环的机制:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
假设您要在单个链表中搜索元素 x
def search(self, x):
position = 1
p =self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, "not found in list")
return False
因此,如果 while 条件失败 else 将执行,希望它有所帮助!
while
语句的 else:
子句不会改变代码的行为。
break
语句 的 while
块之后的 else:
子句是没有意义的——它不会改变代码的行为。
在 Python 中更好地使用 'while: else:' 构造应该是如果在 'while' 中没有执行循环,则执行 'else' 语句。它今天的工作方式没有意义,因为您可以使用下面的代码获得相同的结果......
n = 5
while n != 0:
print n
n -= 1
print "what the..."
break
或 return
关键字离开循环,则不会执行 else
块。在您的示例中,如果循环在 break
命令上结束,也会执行 print
。
据我所知,在任何语言的循环中添加 else 的主要原因是在迭代器不在您的控制范围内的情况下。想象一下,迭代器在服务器上,您只需给它一个信号以获取接下来的 100 条数据记录。只要接收到的数据长度为 100,就希望循环继续。如果小于,则需要再循环一次,然后结束它。在许多其他情况下,您无法控制最后一次迭代。在这些情况下可以选择添加 else 让一切变得更容易。
else:
子句不运行的唯一时间是您跳出循环时,因此此示例不调用这样的构造。即,else:
块内的任何代码都可能不需要 else:
语句(对于本示例)。
while {} something
完全相同 除了 如果您在break
中将跳过something
while
循环。