4

I find myself using this code pattern quite a bit, and every time I do I think there might be a better, clearer way of expressing 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

So essentially, "plan on doing something but if this particular condition is found anytime, anywhere, don't do it"

Maybe this code is perfectly fine, but I wanted to see if anyone had a better suggestion.

Thanks for any input

4

1 回答 1

9

Pythonfor循环可以有一个else块,如果这些循环没有中断,则执行该块:

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

此代码的工作方式与您的相同,但不需要标志。我认为这符合您对更优雅的东西的标准。

于 2013-05-11T17:29:13.200 回答