bassam ch
bassam ch

Reputation: 1

Why does "break" behave like it does in the following piece of code?

count = 1
i = 3
while count != 1000:
     for k in range(2,i):
          if i%k == 0:       
              break
     else:
          print(i)
          count += 1
     i += 2        

In this piece of python code, if break is executed the program will jump over to adding i += 2, is it not supposed to execute else first?

Given that else is not indented to the same level of if and thus does not make part of the for loop.

Upvotes: 0

Views: 125

Answers (2)

Red
Red

Reputation: 27577

The break is for when the program found the k it wanted.
If it doesn't break, k will get larger due to the iteration.
Let's say at iteration 10, i / k leaves no remainder, we want that specific k.
If a for loop ends with a break,
the else statement gets ignored, otherwise, the else statement gets launched.

Upvotes: 0

bigbounty
bigbounty

Reputation: 17408

From python docs - https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Hence, the break statement skips the else clause, and the next statement to execute is i += 2

Upvotes: 1

Related Questions