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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…