Re: Understanding while...else...

Discussion in 'Python' started by Terry Reedy, Jan 22, 2013.

  1. Terry Reedy

    Terry Reedy Guest

    On 1/22/2013 3:09 PM, Ethan Furman wrote:
    > On 01/22/2013 09:44 AM, Terry Reedy wrote:
    >> Several people have trouble understanding Python's while-else and
    >> for-else constructs. It is actually quite simple if one starts with
    >> if-else, which few have any trouble with.
    >>
    >> Start with, for example
    >>
    >> if n > 0:
    >> n -= 1
    >> else:
    >> n = None
    >>
    >> The else clause is executed if and when the condition is false. (That
    >> the code is useless is not the point here.) Now use pseudo-Python label
    >> and goto statements to repeatedly decrement n
    >>
    >> label: check
    >> if n > 0:
    >> n -= 1
    >> goto: check
    >> else:
    >> n = None
    >>
    >> The else clause is executed if and when the condition is false.
    >> Now use a real Python while statement to do the *same
    >> thing*.
    >>
    >> while n > 0:
    >> n -= 1
    >> else:
    >> n = None

    >
    > I understand how it works (although it did take a while for it to sink
    > in); my gripe, and probably why it is misunderstood so often, is that
    > nine times out of ten when I /want/ to use a while-else or for-else I
    > only want the true/false check /once/, at the beginning of the loop.


    I do not understand what you are saying. There already is only one
    true/false check, at the beginning of the loop. If you only want the
    check *performed* once, you would use if-else. But I presume you know this.

    --
    Terry Jan Reedy
    Terry Reedy, Jan 22, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gergely Kontra
    Replies:
    16
    Views:
    217
    Devin Mullins
    Sep 20, 2005
  2. Terry Reedy

    Understanding while...else...

    Terry Reedy, Jan 22, 2013, in forum: Python
    Replies:
    0
    Views:
    101
    Terry Reedy
    Jan 22, 2013
  3. Ethan Furman

    Re: Understanding while...else...

    Ethan Furman, Jan 22, 2013, in forum: Python
    Replies:
    0
    Views:
    109
    Ethan Furman
    Jan 22, 2013
  4. Oscar Benjamin

    Re: Understanding while...else...

    Oscar Benjamin, Jan 23, 2013, in forum: Python
    Replies:
    0
    Views:
    91
    Oscar Benjamin
    Jan 23, 2013
  5. René KlaÄan

    Re: Understanding while...else...

    René KlaÄan, Jan 23, 2013, in forum: Python
    Replies:
    0
    Views:
    100
    René KlaÄan
    Jan 23, 2013
Loading...

Share This Page