[Tutor] (no subject)
Hugo Arts
hugo.yoshi at gmail.com
Tue Feb 7 20:07:30 CET 2012
On Tue, Feb 7, 2012 at 7:50 PM, Debashish Saha <silideba at gmail.com> wrote:
> for i in range(1, 8):
> print(i)
> if i==3:
> break
> else:
> print('The for loop is over')
>
>
> Output:
> 1
> 2
> 3
>
> Question:but after breaking the for loop why the else command could not work?
>
because the else statement was designed to be that way:
http://docs.python.org/reference/compound_stmts.html#for
quoting the relevant part:
"When the items are exhausted (which is immediately when the sequence
is empty), the suite in the else clause, if present, is executed, and
the loop terminates.
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite."
in short, the else clause only executes if you do *not* break out of the loop.
HTH,
Hugo
More information about the Tutor
mailing list