简体   繁体   English

中途停止while循环-Python

[英]Stopping a while loop mid-way - Python

What is the best way to stop a 'while' loop in Python mid-way through the statement? 在语句中途停止“ while”循环的最佳方法是什么? I'm aware of break but I thought using this would be bad practice. 我知道会break但是我认为使用该行将是一种不好的做法。

For example, in this code below, I only want the program to print once, not twice... 例如,在下面的这段代码中,我只希望程序打印一次,而不是两次...

variable = ""
while variable == "" :
    print("Variable is blank.")

    # statement should break here...

    variable = "text"
    print("Variable is: " + variable)

Can you help? 你能帮我吗? Thanks in advance. 提前致谢。

break is fine, although it is usually used conditionally. break是可以的,尽管通常有条件地使用它。 Used unconditionally, it raises the question of why a while loop is used at all: 无条件使用它会引发一个问题,为什么根本使用while循环:

# Don't do this
while condition:
    <some code>
    break
    <some unreachable code>

# Do this
if condition:
    <some code>

Used conditionally, it provides a way of testing the loop condition (or a completely separate condition) early: 有条件地使用它提供了一种早期测试循环条件(或完全独立的条件)的方法:

while <some condition>:
    <some code>
    if <other condition>:
        break
    <some more code>

It is often used with an otherwise infinite loop to simulate the do-while statement found in other languages, so that you can guarantee the loop executes at least once. 它通常与其他无限循环一起使用,以模拟其他语言中的do-while语句,因此您可以保证循环至少执行一次。

while True:
    <some code>
    if <some condition>:
        break

rather than 而不是

<some code>
while <some condition>:
    <some code>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM