Python while 语句中的 Else 子句
- 2024-12-16 08:35:00
- admin 原创
- 156
问题描述:
我注意到以下代码在 Python 中是合法的。我的问题是为什么?有什么具体原因吗?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
许多初学者在尝试将if
/块放入或循环else
内时会意外地遇到此语法,并且没有正确缩进。解决方案是确保块与对齐,假设您打算将它们配对。这个问题解释了为什么它不会导致语法错误,以及生成的代码意味着什么。另请参阅我收到 IndentationError。我该如何修复它? ,了解报告语法错误的情况。while
`forelse
else`if
另请参阅为什么 python 在 for 和 while 循环后使用“else”?以了解有关如何充分利用该功能的问题。
解决方案 1:
仅当条件被评估为假else
时,才会执行该子句。while
因此,如果您break
退出循环,或者引发异常,则else
不会执行(因为while
条件尚未被评估为假)。
思考它的一种方法是将其视为与条件相关的 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()
解决方案 2:
else
如果您正常退出块(通过满足循环条件或脱离 try 块的底部),则会执行该子句。如果您退出块或引发异常,则不会执行该子句。它不仅适用于 while 和 for 循环,也适用于 try 块。break
`return`
您通常会在通常会提前退出循环的地方发现它,而循环结束时运行是一种意外/不寻常的情况。例如,如果您正在循环遍历列表以查找值:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
解决方案 3:
请允许我举一个例子来说明为什么要使用此else
子句。但是:
我的观点在Leo 的回答中得到了更好的解释
我使用
for
- 而不是while
-loop,但else
工作原理类似(除非遇到中断,否则执行)有更好的方法可以做到这一点(例如将其包装到函数中或引发异常)
打破多层循环
它的工作原理如下:外循环在末尾有一个 break,因此它只会执行一次。但是,如果内循环完成(未找到除数),则它会到达 else 语句,并且永远不会到达外循环 break。这样,内循环中的 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!'
解决方案 4:
当 while 条件计算结果为假时,执行 else 子句。
来自文档:
while 语句用于只要表达式为真就重复执行:
while_stmt ::= "while" expression ":" suite ["else" ":" suite]
这将重复测试表达式,如果为真,则执行第一个套件;如果表达式为假(这可能是第一次测试),
else
则执行子句的套件(如果存在)并且循环终止。第一个语句组内的语句
break
会终止循环而不执行else
子句的语句组。continue
第一个语句组内的语句会跳过该语句组的其余部分并返回测试表达式。
解决方案 5:
仅当while 条件变为假时,才会执行 else 子句。
以下是一些示例:
例 1:最初条件为假,因此执行else 子句。
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
输出:
this
例 2:由于中断了循环,while 条件 永远i < 5
不会变为假,因此else 子句不会被执行。i == 3
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
输出:
0
1
2
3
例 3:当时, while条件 i < 5
变为假,因此执行else 子句。i
`5`
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
输出:
0
1
2
3
4
this
解决方案 6:
我的回答将重点关注何时可以使用 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'
有一个break
`while`
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
不属于此类,因为它对上述两种情况的效果相同。
异常引发也不会造成差异,因为当它引发时,下一段将执行的代码是在异常处理程序(except 块)中,else
子句中或子句之后的代码while
将不会被执行。
解决方案 7:
我知道这是一个老问题但是......
正如 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
现在,我们可以交换 while 循环后的条件else
并取消该检查。
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
我总是阅读它来while/no_break
理解代码,并且该语法对我来说更有意义。
解决方案 8:
thing = 'hay'
while thing:
if thing == 'needle':
print('I found it!!') # wrap up for break
break
thing = haystack.next()
else:
print('I did not find it.') # wrap up for no-break
可能不幸命名的else
-clause 是您在不中断的情况下结束循环耗尽的地方。
如果在这种情况下没有什么可做的,则不需要
else
-clause你用
return
orraise
→ 调用后的整个代码或者try
你的 no-break 位置您可以在
else
之前设置默认值while
(例如found = False
)但它会引起与处理默认相关的错误
-clause
else
可以帮你避免这些错误
如果您使用具有非平凡总结的多个中断,则应在中断之前使用简单赋值,else
在不中断的情况下使用 -clause 赋值,以及使用if
- elif
-else
或match
-case
以避免重复非平凡的中断处理代码。
注意:以上所有内容也适用于for thing in haystack:
解决方案 9:
如果 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
解决方案 10:
else:
当且仅当 while 循环不再满足其条件时(在您的示例中,whenn != 0
为假),才会执行该语句。
因此输出将是这样的:
5
4
3
2
1
what the...
解决方案 11:
Python 中“while: else:”构造的更好用法应该是,如果“while”中没有执行循环,则执行“else”语句。它今天的工作方式毫无意义,因为您可以使用下面的代码获得相同的结果……
n = 5
while n != 0:
print n
n -= 1
print "what the..."
解决方案 12:
据我所知,在任何语言中,向循环中添加 else 的主要原因是当迭代器不在您的控制范围内时。假设迭代器在服务器上,您只需给它一个信号来获取接下来的 100 条数据记录。只要收到的数据长度为 100,您希望循环继续。如果少于 100,您需要再执行一次然后结束。还有许多其他情况,您无法控制最后一次迭代。在这些情况下,可以选择添加 else,这会让一切变得容易得多。
解决方案 13:
假设你需要在单个链接列表中搜索元素 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 条件不满足,则将执行其他操作,希望对您有所帮助!
扫码咨询,免费领取项目管理大礼包!