The best pythonic idiom for this repeating piece of code

I use this code quite often, and every time I do this, I think there may be a better and clearer way to express myself:

do_something = True # Check a lot of stuff / loops for thing in things: .... if (thing == 'something'): do_something = False break if (do_something): # Do something 

Essentially, β€œplan to do something, but if this particular condition is found anytime, anywhere, don't do it”

This code might work fine, but I wanted to see if anyone has a better suggestion.

Thanks for any input.

+4
source share
1 answer

Python for loops can have an else block that executes if this loop is not broken:

 for thing in things: ... if (thing == 'something'): break else: ... # Do something 

This code will work just like yours, but don't need a flag. I think it matches your criteria for something more elegant.

+9
source

Source: https://habr.com/ru/post/1480266/


All Articles