Python while语句的其他子句
我注意到以下代码在Python中是合法的。我的问题是为什么?是否有特定原因?
n = 5while n != 0:
print n
n -= 1
else:
print "what the..."
回答:
else仅当你的while条件为假时才执行该子句。如果你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()
以上是 Python while语句的其他子句 的全部内容, 来源链接: utcz.com/qa/402548.html