Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if: else: and if: continue [closed]

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?

like image 446
leafystar Avatar asked Apr 30 '26 11:04

leafystar


1 Answers

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.

like image 97
Andronicus Avatar answered May 02 '26 23:05

Andronicus