Reputation: 1600
I'm curious which of the following is considered better form. My examples are snippets, but in more complex programs I've written, I can see arguments for and have used either.
Option 1: Skip ahead if a condition is met, otherwise execute lots of code:
for i in range(5):
if i == 3:
continue
print i
# and do lots of other stuff
The argument for this: clearly skips certain condition, doesn't result in overly nested code.
Option 2: Execute lots of code if condition is not met:
for i in range(5):
if i is not 3:
print i
# and do lots of other stuff
The argument for this: more verbose and doesn't use unnecessary continue
.
(There seems to be a few questions related to this, but mostly about using functions or long blocks of code. I'm curious about the ==
vs !=
part.)
Upvotes: 0
Views: 29
Reputation: 55664
I think that, generally, Option 1 is better practice. In Option 2, 'lots of other stuff' is at a second level on indentation. Generally, the less indentation, the better.
Upvotes: 1