[英]Stopping a while loop mid-way - Python
在语句中途停止“ while”循环的最佳方法是什么? 我知道会break
但是我认为使用该行将是一种不好的做法。
例如,在下面的这段代码中,我只希望程序打印一次,而不是两次...
variable = ""
while variable == "" :
print("Variable is blank.")
# statement should break here...
variable = "text"
print("Variable is: " + variable)
你能帮我吗? 提前致谢。
break
是可以的,尽管通常有条件地使用它。 无条件使用它会引发一个问题,为什么根本使用while
循环:
# Don't do this
while condition:
<some code>
break
<some unreachable code>
# Do this
if condition:
<some code>
有条件地使用它提供了一种早期测试循环条件(或完全独立的条件)的方法:
while <some condition>:
<some code>
if <other condition>:
break
<some more code>
它通常与其他无限循环一起使用,以模拟其他语言中的do-while
语句,因此您可以保证循环至少执行一次。
while True:
<some code>
if <some condition>:
break
而不是
<some code>
while <some condition>:
<some code>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.