Not sure why break is not implemented in this simple code

numbers= [12,75,150,180,145,525,50]
for item in numbers:
    if item>150:
        continue
    if item>500:
        break
    if item%5==0:
        print(item)

So when I run this, the output should ignore the value 50 because the value 525 should have caused the loop to break beforehand. The output is 75, 150, 145, 50 but should’nt be including the last 50 integer. Thanks!

Dave

The second conditional will never be reached because any number bigger than 500 is also bigger than 150.

Thanks for the reply! In your response, but doesnt the continue operation just skip ahead to the next item in the list? It will see 12 (ignore), 75 (print), 150 (print), 180 (continue), 145 (print), 525 (break- leave loop) no?

The point is, though, that when item is 525, the first condition evaluates to True, so the next condition (item > 500) isn’t evaluated.

1 Like

Correct. So when the item is 525, the continue is reached. At that point the loop is restarted with the next item (50).

If you rearrange the first two conditionals, it will work how you want. Items over 500 will break out, and items between 500 and 150 will be ignored.

1 Like

Thanks! So generally the order of the conditionals should be the break ones first then the continues I gather.

Cheers

No, it has nothing to do with the ordering of breaks and continues but the ordering of overlapping conditions where entering one prevents entering the other.

The order is dictated by what you need to have happen.

If we note that using break or continue skips the rest of the loop
body, you can write your loop body like this:

 if item>150:
     continue
 elif item>500:
     break
 elif item%5==0:
     print(item)

Is the effect more clear now? The item>150 precludes consideration
of the item>500 if it matches.

Cheers,
Cameron Simpson cs@cskk.id.au

2 Likes

Thanks, so in your example- for item 525 the code would still not break out, it would continue and print item 50 right?

Correct. The logic is unchanged, I’ve just made the pick-only-one-branch
which it effects more overt by using elif.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like