Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

Stopping a while loop mid-way - Python

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...