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