2

Why is the break needed in the following code to skip processing of the else statement? Why doesn't the if evaluation exit the program by itself, without continuing to process the else statement as well? Is it because the if is nested in a for loop? If so, why is that? I can't figure out why this works this way.

code:

for number in range(1,10):
   if number == 5:
       print "I counted to %s" % number
else:
   print "I counted from 1 to 10"

output:

I counted to 5 I counted from 1 to 10

code:

for number in range(1,10):
   if number == 5:
       print "I counted to %s" % number
       break
else:
   print "I counted from 1 to 10"

output:

I counted to 5

Lucien Semyon
  • 21
  • 1
  • 2

1 Answers1

1

You need to check Python's official document on: "break and continue Statements, and else Clauses on Loops" which says:

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 list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126