for what are for/while else clauses

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Diez B. Roggisch

    for what are for/while else clauses

    Hi,

    today I rummaged through the language spec to see whats in the for ... else:
    for me. I was sort of disappointed to learn that the else clauses simply
    gets executed after the loop-body - regardless of the loop beeing entered
    or not.

    So where is an actual use case for that feature?

    I imagined that the else-clause would only be executed if the loop body
    wasn't entered, so I could write this

    for r in result:
    print r
    else:
    print "Nothing found, dude!"

    instead of

    if len(result):
    for r in result
    print r
    else:
    print "Nothing found, dude!"



    waiting for enlightment,

    Diez
  • David C. Fox

    #2
    Re: for what are for/while else clauses

    Diez B. Roggisch wrote:
    [color=blue]
    > Hi,
    >
    > today I rummaged through the language spec to see whats in the for ... else:
    > for me. I was sort of disappointed to learn that the else clauses simply
    > gets executed after the loop-body - regardless of the loop beeing entered
    > or not.[/color]

    I didn't realize that for...else existed, but according to the language
    reference, the else clause gets executed unless the loop body exited due
    to a break statement.

    David

    Comment

    • John Roth

      #3
      Re: for what are for/while else clauses


      "David C. Fox" <davidcfox@post .harvard.edu> wrote in message
      news:nr9tb.2005 90$Fm2.189136@a ttbi_s04...[color=blue]
      > Diez B. Roggisch wrote:
      >[color=green]
      > > Hi,
      > >
      > > today I rummaged through the language spec to see whats in the for ...[/color][/color]
      else:[color=blue][color=green]
      > > for me. I was sort of disappointed to learn that the else clauses simply
      > > gets executed after the loop-body - regardless of the loop beeing[/color][/color]
      entered[color=blue][color=green]
      > > or not.[/color]
      >
      > I didn't realize that for...else existed, but according to the language
      > reference, the else clause gets executed unless the loop body exited due
      > to a break statement.[/color]

      Yep. It's one of the three termination conditions for a loop. The problem
      is that it's a really bad name, and the termination condition I'm most
      interested
      in catching is the one where the loop didn't execute at all.

      John Roth
      [color=blue]
      >
      > David
      >[/color]


      Comment

      • JCM

        #4
        Re: for what are for/while else clauses

        John Roth <newsgroups@jhr othjr.com> wrote:
        ....[color=blue]
        > Yep. It's one of the three termination conditions for a loop.[/color]

        What are the three conditions? I know of two:

        1 Reaching the end of the iteration
        2 Breaking out

        Comment

        • Rene Pijlman

          #5
          Re: for what are for/while else clauses

          Diez B. Roggisch:[color=blue]
          >today I rummaged through the language spec to see whats in the for ... else:
          >for me. I was sort of disappointed to learn that the else clauses simply
          >gets executed after the loop-body - regardless of the loop beeing entered
          >or not.
          >
          >So where is an actual use case for that feature?[/color]

          To execute code only when the loop terminates normally, not when it
          terminates because of a break statement.

          It's been discussed before:




          --
          René Pijlman

          Comment

          • Fredrik Lundh

            #6
            Re: for what are for/while else clauses

            Diez B. Roggisch wrote:
            [color=blue]
            > today I rummaged through the language spec to see whats in the for ... else:
            > for me. I was sort of disappointed to learn that the else clauses simply
            > gets executed after the loop-body - regardless of the loop beeing entered
            > or not.
            >
            > So where is an actual use case for that feature?[/color]

            for item in seq:
            if item == target_item:
            print "Found", item
            break
            else:
            print "Nothing found, dude!"
            [color=blue]
            > I imagined that the else-clause would only be executed if the loop body
            > wasn't entered, so I could write this
            >
            > for r in result:
            > print r
            > else:
            > print "Nothing found, dude!"
            >
            > instead of
            >
            > if len(result):
            > for r in result
            > print r
            > else:
            > print "Nothing found, dude!"[/color]

            which is usually written as:

            if result:
            for r in result:
            print r
            else:
            print "Nothing found, dude!"

            or

            if not result:
            print "Nothing found, dude!"
            else:
            for r in result:
            print r

            </F>




            Comment

            • John Roth

              #7
              Re: for what are for/while else clauses


              "JCM" <joshway_withou t_spam@myway.co m> wrote in message
              news:bp3bmg$l3$ 1@fred.mathwork s.com...[color=blue]
              > John Roth <newsgroups@jhr othjr.com> wrote:
              > ...[color=green]
              > > Yep. It's one of the three termination conditions for a loop.[/color]
              >
              > What are the three conditions? I know of two:
              >
              > 1 Reaching the end of the iteration
              > 2 Breaking out[/color]
              3. Not executing at all.

              John Roth[color=blue]
              >[/color]


              Comment

              • JCM

                #8
                Re: for what are for/while else clauses

                John Roth <newsgroups@jhr othjr.com> wrote:
                [color=blue]
                > "JCM" <joshway_withou t_spam@myway.co m> wrote in message
                > news:bp3bmg$l3$ 1@fred.mathwork s.com...[color=green]
                >> John Roth <newsgroups@jhr othjr.com> wrote:
                >> ...[color=darkred]
                >> > Yep. It's one of the three termination conditions for a loop.[/color]
                >>
                >> What are the three conditions? I know of two:
                >>
                >> 1 Reaching the end of the iteration
                >> 2 Breaking out[/color]
                > 3. Not executing at all.[/color]

                I see that as an example of #1.

                Comment

                • John Roth

                  #9
                  Re: for what are for/while else clauses


                  "JCM" <joshway_withou t_spam@myway.co m> wrote in message
                  news:bp3ej3$n35 $1@fred.mathwor ks.com...[color=blue]
                  > John Roth <newsgroups@jhr othjr.com> wrote:
                  >[color=green]
                  > > "JCM" <joshway_withou t_spam@myway.co m> wrote in message
                  > > news:bp3bmg$l3$ 1@fred.mathwork s.com...[color=darkred]
                  > >> John Roth <newsgroups@jhr othjr.com> wrote:
                  > >> ...
                  > >> > Yep. It's one of the three termination conditions for a loop.
                  > >>
                  > >> What are the three conditions? I know of two:
                  > >>
                  > >> 1 Reaching the end of the iteration
                  > >> 2 Breaking out[/color]
                  > > 3. Not executing at all.[/color]
                  >
                  > I see that as an example of #1.[/color]

                  But it isn't. See what your code looks like with an
                  empty file, for example. Or even worse, see what it
                  would look like if you have to use a generator where
                  you can't test for an empty sequence.

                  John Roth


                  Comment

                  • Terry Reedy

                    #10
                    Re: for what are for/while else clauses


                    "Diez B. Roggisch" <deets_noospaam @web.de> wrote in message
                    news:bp371c$g75 $07$1@news.t-online.com...[color=blue]
                    > I imagined that the else-clause would only be executed if the loop[/color]
                    body[color=blue]
                    > wasn't entered, so I could write this[/color]
                    ....[color=blue]
                    > waiting for enlightment,[/color]

                    Try the following which I recently thought up.
                    You are familiar with this:

                    if cond: t()
                    else: f()

                    meaning, if cond is false, do f(). Now

                    while cond: t()
                    else: f()

                    means if and when cond is false, do f(). To make the parallel
                    clearer, consider this C-like pseudopython equivalent:

                    label: loop
                    if cond:
                    t()
                    goto loop
                    else: f()

                    If (and now when, because of the looping) cond is false, do f(). Now,

                    for i in seq: t()
                    else: f()

                    translates to something like

                    __i, __istop = 0, len(seq)
                    while __i < __istop:
                    i = seq[__i]
                    t()
                    else: f()

                    which in turn could be translated to an if with goto, so that f
                    executes if/when the sequence is exhausted.

                    In summary, the else clause executes if/when the loop condition
                    evaluates as false, just as with else clauses and if conditions. The
                    difference is the repeated instead of just once testing of the
                    condition. Break aborts this repeated testing and bypasses the else
                    clause, as it should because the condition was always true, as also
                    happens with true if conditions.

                    Terry J. Reedy


                    Comment

                    • Bryan

                      #11
                      Re: for what are for/while else clauses

                      Terry Reedy wrote:[color=blue]
                      > "Diez B. Roggisch" <deets_noospaam @web.de> wrote in message
                      > news:bp371c$g75 $07$1@news.t-online.com...
                      >[color=green]
                      >>I imagined that the else-clause would only be executed if the loop[/color]
                      >
                      > body
                      >[color=green]
                      >>wasn't entered, so I could write this[/color]
                      >
                      > ...
                      >[color=green]
                      >>waiting for enlightment,[/color]
                      >
                      >
                      > Try the following which I recently thought up.
                      > You are familiar with this:
                      >
                      > if cond: t()
                      > else: f()
                      >
                      > meaning, if cond is false, do f(). Now
                      >
                      > while cond: t()
                      > else: f()
                      >
                      > means if and when cond is false, do f(). To make the parallel
                      > clearer, consider this C-like pseudopython equivalent:
                      >
                      > label: loop
                      > if cond:
                      > t()
                      > goto loop
                      > else: f()
                      >
                      > If (and now when, because of the looping) cond is false, do f(). Now,
                      >
                      > for i in seq: t()
                      > else: f()
                      >
                      > translates to something like
                      >
                      > __i, __istop = 0, len(seq)
                      > while __i < __istop:
                      > i = seq[__i]
                      > t()
                      > else: f()
                      >
                      > which in turn could be translated to an if with goto, so that f
                      > executes if/when the sequence is exhausted.
                      >
                      > In summary, the else clause executes if/when the loop condition
                      > evaluates as false, just as with else clauses and if conditions. The
                      > difference is the repeated instead of just once testing of the
                      > condition. Break aborts this repeated testing and bypasses the else
                      > clause, as it should because the condition was always true, as also
                      > happens with true if conditions.
                      >
                      > Terry J. Reedy
                      >
                      >[/color]

                      terry,

                      thnak you for your very clear and consice explanation.

                      bryan

                      Comment

                      • Michele Simionato

                        #12
                        Re: for what are for/while else clauses

                        I personally consider the "else" clause a wart of Python.
                        I never remember exactly what it is doing, and I have to look at the
                        manual each time; moreover I don't see it giving any significant advantage
                        to the language (other languages live very well without). So, I would be
                        happy to have it removed, even if I am sure it will never happen :-(
                        Am I the only one who think so?

                        Michele

                        Comment

                        • Erik Max Francis

                          #13
                          Re: for what are for/while else clauses

                          Michele Simionato wrote:
                          [color=blue]
                          > I personally consider the "else" clause a wart of Python.
                          > I never remember exactly what it is doing, and I have to look at the
                          > manual each time; moreover I don't see it giving any significant
                          > advantage
                          > to the language (other languages live very well without). So, I would
                          > be
                          > happy to have it removed, even if I am sure it will never happen :-(
                          > Am I the only one who think so?[/color]

                          I actually like it, and have used it with the `for' and `while' control
                          structures (although I only recently found out it is also available with
                          `try' and had that functionality to EmPy). For some reason I can always
                          remember what it does, even though I agree it's not very memorable. I
                          will readily admit that `else' is not a particularly enlightening name
                          for the functionality it represents, but I'm not sure I could come up
                          with a one-word substitute that would be much more enlightening.

                          I do think it is highly ironic that a unified try...except... finally
                          construct was removed because it was allegedly not intuitive enough, but
                          for...else, while...else, and even try...except... else (!) stayed with
                          no such complaint.

                          --
                          Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                          __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
                          / \
                          \__/ There's this perfect girl / Someone no one can see
                          -- Lamya

                          Comment

                          • Michele Simionato

                            #14
                            Re: for what are for/while else clauses

                            Erik Max Francis <max@alcyone.co m> wrote in message news:<3FB5D88B. 6FEA580B@alcyon e.com>...[color=blue]
                            > I do think it is highly ironic that a unified try...except... finally
                            > construct was removed because it was allegedly not intuitive enough, but
                            > for...else, while...else, and even try...except... else (!) stayed with
                            > no such complaint.[/color]

                            It is strange that I do feel try...except... else very natural and I use
                            the construct all the time... mah!

                            My complaint is only against else in while and for.

                            Michele

                            Comment

                            • Alex Martelli

                              #15
                              Re: for what are for/while else clauses

                              Michele Simionato wrote:
                              [color=blue]
                              > I personally consider the "else" clause a wart of Python.[/color]

                              I think it depends on what statements we're talking about, but, yes,
                              restricting the discussion to for/else and while/else (if/else and
                              try/except/else being very different) I understand why you would.
                              [color=blue]
                              > I never remember exactly what it is doing, and I have to look at the[/color]

                              I haven't had the problem, myself, but I have seen others believe that the
                              else clause would run if the body was never run (for on an empty sequence,
                              while on a condition that's false since the first check), as in
                              (hypothetically )

                              for item in bought:
                              print 'Bought item', item
                              else:
                              print "No items were bought"

                              being short for

                              if bought:
                              for item in bought:
                              print 'Bought item', item
                              else:
                              print "No items were bought"

                              which might make sense (if bought were a non-reiterable, the if/else
                              construct has problems while the imaginary interpretation of the for/else
                              one would still work just fine). In this way, Python's for/else and
                              while/else do fail the least-astonishment test for at least some learners
                              (taking "else" to mean "no break was executed in the body" is hardly
                              obvious or most particularly "the only obvious" interpretation) .
                              [color=blue]
                              > manual each time; moreover I don't see it giving any significant advantage
                              > to the language (other languages live very well without). So, I would be[/color]

                              The fact that other languages lack a construct isn't necessarily
                              significant, of course -- most lack, e.g., classes as first-class objects,
                              yet Python's vastly better for having them. Still, it is indeed arguable
                              that for/else buys you little -- just a flag setting and checking when you
                              do use it, i.e., at most.
                              [color=blue]
                              > happy to have it removed, even if I am sure it will never happen :-([/color]

                              Right, it's unlikely -- I haven't it seen proposed as a candidate to go
                              away in 3.0.
                              [color=blue]
                              > Am I the only one who think so?[/color]

                              Probably not; even though on the whole I disagree, I don't consider your
                              position at all "strange", nor my opposition particularly strong, therefore
                              I suspect that many at least mildly agree with you.

                              The classic homework one should do when considering a language
                              construct is "how is it used in the standard library". Have you examined
                              the uses of for/else and while/else there?


                              Alex

                              Comment

                              Working...