Let's say I have an iterable: balls. I want to do something to all the balls in that loop that are not blue. As far as I see it I have two options:
Using if: else:
for ball in balls:
if ball.blue:
# can do something with blue ball
else:
# now execute code for all balls that are not blue
Using if: continue
for ball in balls:
if ball.blue:
# can do something with blue ball
continue
# now execute code for all balls that are not blue
To me there is no difference in what can be achieved with these two structures. Is there an intended difference? Are there cases where one is quicker, more readable, etc?
In the case you've shown there is no difference as there is no logic after if-else statement. Generally continue is used to skip to another iteration of for loop, so in the following case you would't be able to translate it so easily:
for ball in balls:
if ball.blue:
# can do something with blue ball
else:
# now execute code for all balls that are not blue
# here some logic
If you would replace else with continue at the end of if, the last line wouldn't be reached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With