Simple if-else question

Chris Kaynor ckaynor at zindagigames.com
Tue Sep 29 11:59:09 EDT 2009


If I'm reading the indentation correctly, the else is applying to the for
loop, not the if statement.

When used in this way, the else occurs only if the for loop exits due to
completion (aka, the for loop does not exit due to a break or return
statement).


I would expect the output from that code to be:
0
1
2
3
7

Any values in the range under 4 should be printed (the if), as well as the
last value in the range (7 in the case given).


Chris


On Tue, Sep 29, 2009 at 8:50 AM, Sandy <dksreddy at gmail.com> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090929/e3e884dd/attachment-0001.html>


More information about the Python-list mailing list