中途停止 while 循环 - Python

Stopping a while loop mid-way - Python

在语句中途停止 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>