Simple if-else question

Ethan Furman ethan at stoneleaf.us
Tue Sep 29 12:09:50 EDT 2009


Sandy wrote:
> Hi all,
> A simple and silly if-else question.
> I saw some code that has the following structure. My question is why
> else is used there though removing else
> has the same result. More important, is it not syntactically wrong :-(
> 
> for i in xrange(8):
>     if i < 4:
>         print i
> else:
>     print i
> 
> Cheers,
> dksr

The else is not tied to the if, it is tied to the for.  The statements 
in a for-else (and while-else, and if-else) only execute if the control 
expression becomes False.  If you want to avoid executing the else 
clause, you have to break out of the loop.

Some examples:

In [1]: for i in xrange(8):
    ...:     if i < 4:
    ...:         print i
    ...:
0
1
2
3

In [2]: for i in xrange(8):
    ...:     if i < 4:
    ...:         print i
    ...: else:
    ...:     print i
    ...:
0
1
2
3
7

In [3]: for i in xrange(8):
    ...:     if i < 4:
    ...:         print i
    ...:     if i == 1:
    ...:         break
    ...: else:
    ...:     print i
    ...:
0
1

Hope this helps!

~Ethan~



More information about the Python-list mailing list