There no way to break out of only the inner loop of a next loop in #python?
for i in range(1,100)
while True:
print("whut?")
break # what?
Conversation
Replying to
If you want to break out of the inner While loop, but not the outer for loop. Or if you want to break out of the outer for loop when you are in the middle of the inner loop. Other languages have features for this. stackoverflow.com/a/504983/33264
1
Replying to
for x in range(1,10):
while True:
print(x)
break
This gives me the output (1,2,3,4,5,6,7,8,9) which I would expect. It is breaking out of the inner while loop but staying in the outer for loop. What output would you expect?
1
Replying to
Not saying the behavior was undefined. Without syntax python lacks, it can only break out of the inner loop then. As a casual reader or a maintenance dev, I'd always assume that the original developer didn't know what would happen-an inner or outer loop break (1) vs (1,2...9)
2
1
Replying to
Ahhh ok -- I see what you're saying now. Yeah, I think that's a limitation of Python that should eventually get addressed in some way.
I've never found its behavior confusing, but I suppose others could. Outer loop breaks can be achieved by setting a boolean flag before breaking or with for/else, but usually better to extract a function in this case.
1
2
Good point. As someone who has programmed in multiple different languages, I always find there's a feature in another language that is lacking in another one. Some are trivial (like no variable++ increment in Python -- but variable+=1 ... minor nitpicks, etc.)
1


