Else statement executing when it shouldnt

Thomas Boell tboell at domain.invalid
Tue Jan 22 16:39:24 CET 2013


On Mon, 21 Jan 2013 06:07:08 +0100
René Klačan <rene.klacan at gmail.com> wrote:

> Examples:
> 
> # else branch will be executed
> i = 0
> while i < 5:
>     i += 1
> else:
>     print('loop is over')
> 
> 
> # else branch will be executed
> i = 0
> while i < 5:
>     i += 1
>     if i == 7:
>         print('i == 7')
>         break
> else:
>     print('loop is over')
> 
> 
> # else branch wont be executed
> i = 0
> while i < 5:
>     i += 1
>     if i == 3:
>         print('i == 3')
>         break
> else:
>     print('loop is over')

Huh?! I would have expected all your examples to raise a SyntaxError or
IndentationError. Why don't they? Is 'else' not required to have a
matching 'if'?




More information about the Python-list mailing list