Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What is the best way to stop a 'while' loop in Python mid-way through the statement? I'm aware of break but I thought using this would be bad practice.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

break is fine, although it is usually used conditionally. Used unconditionally, it raises the question of why a while loop is used at all:

# 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.

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

rather than

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...