Python Use while loop to escape complex if statements

4 days ago 7
ARTICLE AD BOX

It looks like you are trying to emulate the well-established pattern of "returning early" from a function, but without using a function. The only reason you use a while loop is so that you have something to break-early out of, and the loop only has one iteration. I would say just wrap your code in a function, and use early returns, as that is more idiomatic:

def should_perform_action(self) -> bool: if self.is_empty(): return False if self._index > self._count: return False return True # ... if self.should_perform_action(): # ...

Paul M.'s user avatar

Yes, break is generally intended to escape loops along with continue to skip the rest of a loop.. though if the loop is either logically only executed once and/or more generally if you find you have a lot of break statements and then do more work after a loop, consider packing it all into a function and returning early instead as @Paul M. notes

Otherwise for and while also offer else: for when they did not break, though I'm not sure I've ever seen it used by the latter

for index in range(10): if index < 3: continue if index > 5: break else: print("didn't break")

Official docs https://docs.python.org/3/reference/compound_stmts.html#while

ti7's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article