-3

In the image attached, when i=3, why does the "break" take us to the final print("Out side the loop")? Why doesn't it jump to the part:

else: 
    print ("Loop terminates with success")?

I am struggling to understand this.

bz_2020
  • 79
  • 1
  • 14
  • 1
    Please avoid posting images (or worse, links to images) of code or errors. Anything text-based (code and errors) should be posted as text directly in the question itself and formatted properly. You can get more [formatting help here](https://stackoverflow.com/help/formatting). You can also read about [why you shouldn't post images/links of code](//meta.stackoverflow.com/q/285551). – Tomerikoo Nov 30 '20 at 12:47
  • Because that's exactly how [`for/else`](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) works: *loop’s `else` clause runs when __no__ `break` occurs.* – Tomerikoo Nov 30 '20 at 12:54
  • @LouieC it will also print that if `S` was of size 1... – Tomerikoo Nov 30 '20 at 12:55

1 Answers1

1

for...else loops only run the else when the loop terminates normally and a break is not encountered. So, it skips the else since the loop was ended early.

Aplet123
  • 33,825
  • 1
  • 29
  • 55