Loop until condition is true

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Remi Villatel

    #1

    Loop until condition is true

    Hi there,

    There is always a "nice" way to do things in Python but this time I can't
    find one.

    What I'm trying to achieve is a conditionnal loop of which the condition
    test would be done at the end so the loop is executed at least once. It's
    some way the opposite of "while".

    So far, all I got is:

    while True:
    some(code)
    if final_condition is True:
    break
    #
    #

    What I don't find so "nice" is to have to build an infinite loop only to
    break it.

    Is there a better recipe?

    --
    =============== ===
    Remi Villatel
    maxilys_@_tele2 .fr
    =============== ===
  • Donn Cave

    #2
    Re: Loop until condition is true

    Quoth Remi Villatel <maxilys@SPAMCO P_tele2.fr>:

    | What I'm trying to achieve is a conditionnal loop of which the condition
    | test would be done at the end so the loop is executed at least once. It's
    | some way the opposite of "while".
    |
    | So far, all I got is:
    |
    | while True:
    | some(code)
    | if final_condition is True:
    | break
    | #
    | #
    |
    | What I don't find so "nice" is to have to build an infinite loop only to
    | break it.
    |
    | Is there a better recipe?

    It depends, but that isn't too bad. The alternative would be flag
    variable, like "looping = 1; while looping: ..."

    The construct you're looking for is "until" in C, and there have been
    plenty of proposals to add this or other improvements to Python's
    repertoire. As far as I know, it hasn't happened because it isn't
    really needed. If you look at C code, at least in my experience the
    "until" loop is quite rarely used. (I don't see it once in the source
    to Python 2.4, for example.) Meanwhile, the "while True" (or "while 1")
    idiom is very familiar to Python programmers (just as the Python source
    has dozens of "for (;;)"), so it's preferred for legibility. It's nice,
    don't worry.

    Donn Cave, donn@drizzle.co m

    Comment

    • Peter Otten

      #3
      Re: Loop until condition is true

      Donn Cave wrote:
      [color=blue]
      > If you look at C code, at least in my experience the
      > "until" loop is quite rarely used.  (I don't see it once in the source
      > to Python 2.4, for example.)[/color]

      Long time no C?

      'until' in C is actually

      do
      statement
      while (expression);

      I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for
      (" in the Python 2.4 source, so using these rough estimates do-while still
      qualifies as "rarely used".

      Peter

      Comment

      • Grant Edwards

        #4
        Re: Loop until condition is true

        On 2005-06-18, Peter Otten <__peter__@web. de> wrote:
        [color=blue][color=green]
        >> If you look at C code, at least in my experience the
        >> "until" loop is quite rarely used.  (I don't see it once in the source
        >> to Python 2.4, for example.)[/color]
        >
        > Long time no C?
        >
        > 'until' in C is actually
        >
        > do
        > statement
        > while (expression);
        >
        > I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for
        > (" in the Python 2.4 source, so using these rough estimates do-while still
        > qualifies as "rarely used".[/color]

        AFAICT, the main use for do/while in C is when you want to
        define a block of code with local variables as a macro:

        #define DoSomething(foo ) \
        do \
        { \
        int i; \
        /* do something with foo and i */ \
        } while (0)

        --
        Grant Edwards grante Yow! I HIJACKED a 747 to
        at get here!! I hope those
        visi.com fabulous CONEHEADS are
        at HOME!!

        Comment

        • Tim Williams

          #5
          Re: Loop until condition is true


          ----- Original Message -----
          From: "Remi Villatel" <maxilys@SPAMCO P_tele2.fr>

          [color=blue]
          > There is always a "nice" way to do things in Python but this time I can't
          > find one.[/color]
          [color=blue]
          > So far, all I got is:
          >
          > while True:
          > some(code)
          > if final_condition is True:
          > break
          > #
          > #
          >
          > What I don't find so "nice" is to have to build an infinite loop only to
          > break it.[/color]

          If your final_condition is already defined outside the "while" then how
          about

          while not final_condition :
          some(code)

          Simplistically, this equates to
          [color=blue][color=green][color=darkred]
          >>> x = 0
          >>> while not x == 5:[/color][/color][/color]
          .... x += 1
          ....[color=blue][color=green][color=darkred]
          >>> print x[/color][/color][/color]
          5

          :)

          Comment

          • Donn Cave

            #6
            Re: Loop until condition is true

            Quoth Peter Otten <__peter__@web. de>:
            ....
            | 'until' in C is actually
            |
            | do
            | statement
            | while (expression);

            Oops. Well, QED - I sure don't need it often.

            Donn Cave, donn@drizzle.co m

            Comment

            • Andrea Griffini

              #7
              Re: Loop until condition is true

              On Sat, 18 Jun 2005 13:35:16 -0000, Grant Edwards <grante@visi.co m>
              wrote:
              [color=blue]
              >AFAICT, the main use for do/while in C is when you want to
              >define a block of code with local variables as a macro:[/color]

              When my job was squeezing most out of the CPU (videogame
              industry) I remember that the asm code generated by

              while (sz-- > 0)
              {
              /* do some stuff */
              }

              was indeed worse than

              do
              {
              /* do some stuff */
              } while (--sz);

              because of the initial "empty-loop" test (conditional jumps
              were bad, and forward conditional jumps were worse).
              So where at least one iteration was guaranteed the do-while
              loop was a better choice.

              Also I've been told there were compilers that if using
              for or while loops the generated code was

              <initialize>
              L1:
              <evaluate condition>
              je L2
              <body>
              jmp L1
              L2:

              Instead the do-while loop would have been

              L1:
              <body>
              <evaluate condition>
              jne L1

              I.e. the code was better *for each iteration* (one conditional
              jump instead of one conditional jump and one inconditional jump).

              I think compiler got better since then, even if I don't think
              they already so smart to be able to infer the "one interation
              guaranteed" property to avoid the initial test that often.

              Andrea

              Comment

              • Michael J. Fromberger

                #8
                Re: Loop until condition is true

                In article <nha8b11f7c0ca8 t2r7acopqb9uqm3 gbqlm@4ax.com>,
                Andrea Griffini <agriff@tin.i t> wrote:
                [color=blue]
                > On Sat, 18 Jun 2005 13:35:16 -0000, Grant Edwards <grante@visi.co m>
                > wrote:
                >[color=green]
                > >AFAICT, the main use for do/while in C is when you want to
                > >define a block of code with local variables as a macro:[/color]
                >
                > When my job was squeezing most out of the CPU (videogame
                > industry) I remember that the asm code generated by
                >
                > while (sz-- > 0)
                > {
                > /* do some stuff */
                > }
                >
                > was indeed worse than
                >
                > do
                > {
                > /* do some stuff */
                > } while (--sz);
                >
                > because of the initial "empty-loop" test (conditional jumps
                > were bad, and forward conditional jumps were worse).
                > So where at least one iteration was guaranteed the do-while
                > loop was a better choice.[/color]

                Hmm. I don't know what compiler you were using, but in my experience
                it's fairly typical to compile while(<test> ...) { <body> ... } as

                j test
                body: <body>
                ...
                test: <test>
                ...
                je body ;; or whatever your condition is

                To turn this into a do { <body> ... } while(<test> ...), you need only
                remove the initial "j test" instruction. Even if forward conditional
                jumps are bad for your particular architecture, this method avoids the
                problem neatly.

                Personally, I'd be pretty suspicious of the quality of a compiler that
                produced radically different code for these two constructs without some
                damned good reason.

                -M

                --
                Michael J. Fromberger | Lecturer, Dept. of Computer Science
                http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA

                Comment

                • Magnus Lycka

                  #9
                  Re: Loop until condition is true

                  Remi Villatel wrote:[color=blue]
                  > while True:
                  > some(code)
                  > if final_condition is True:
                  > break
                  > #
                  > #
                  >
                  > What I don't find so "nice" is to have to build an infinite loop only to
                  > break it.[/color]

                  This is a common Python idiom. I think you will get used to it.

                  [color=blue]
                  > Is there a better recipe?[/color]

                  final_condition = False
                  while not final_condition :
                  some(code)

                  Comment

                  • Benji York

                    #10
                    Re: Loop until condition is true

                    Cyril BAZIN wrote:[color=blue]
                    > Another question could be: why is there not a statement "whileTrue" or
                    > "loop"?[/color]

                    I don't think the saving of a single space to transform "while True:"
                    into "WhileTrue: " is really worth it. The same goes for "loop", the
                    added complexity to the language (as little as it is) isn't rewarded by
                    a large enough improvement to make it worth it.
                    [color=blue]
                    > It could be an economy of one unuseful test by loop.[/color]

                    If by "economy" you mean "optimizati on", then I would suggest that the
                    difference would be unnoticeable.
                    --
                    Benji York

                    Comment

                    • Charles Krug

                      #11
                      Re: Loop until condition is true

                      On Tue, 21 Jun 2005 12:05:25 +0200, Magnus Lycka <lycka@carmen.s e> wrote:[color=blue]
                      > Remi Villatel wrote:[color=green]
                      >> while True:
                      >> some(code)
                      >> if final_condition is True:
                      >> break
                      >> #
                      >> #
                      >>
                      >> What I don't find so "nice" is to have to build an infinite loop only to
                      >> break it.[/color]
                      >
                      > This is a common Python idiom. I think you will get used to it.
                      >
                      >[color=green]
                      >> Is there a better recipe?[/color]
                      >
                      > final_condition = False
                      > while not final_condition :
                      > some(code)[/color]

                      To the OP, don't get hung up on the syntax we use to implement a loop.

                      I took my first programming class long enough ago that we had to do
                      things like this (roughly translating the FORTRAN IV I remember into
                      p-code)

                      To do:

                      while TrueCondition
                      (loop body)

                      we'd have to write:

                      TopOfLoop:
                      if not TrueConditional goto loopEnd
                      (loop body)
                      goto TopOfLoop

                      loopEnd:

                      We were even required to write our source twice:

                      The first pass was "structured " and had to be proven correct.

                      The second pass was translated into something our compiler supported.

                      We still called it a "while loop" even though the syntax was icky.

                      When C came out with its built in looping, it was an unbelievable
                      luxury.

                      Comment

                      • Magnus Lycka

                        #12
                        Re: Loop until condition is true

                        Benji York wrote:[color=blue]
                        > If by "economy" you mean "optimizati on", then I would suggest that the
                        > difference would be unnoticeable.[/color]

                        If there is a measurable performance gain in skipping the runtime
                        test in "while True", then this is a compiler issue, not a language
                        issue. I don't know anything about the Python compiler internals,
                        but it doesn't seem very hard to identify simple literals following
                        while and if, and to skip the runtime test. (Perhaps it's done
                        already?)

                        I hope the time is over when language designers build ugly quirks
                        into programming language syntaxes to make life a little easier for
                        the compilers.

                        Comment

                        • Fredrik Lundh

                          #13
                          Re: Loop until condition is true

                          Remi Villatel wrote:
                          [color=blue]
                          > There is always a "nice" way to do things in Python but this time I can't
                          > find one.
                          >
                          > What I'm trying to achieve is a conditionnal loop of which the condition
                          > test would be done at the end so the loop is executed at least once. It's
                          > some way the opposite of "while".
                          >
                          > So far, all I got is:
                          >
                          > while True:
                          > some(code)
                          > if final_condition is True:
                          > break
                          > #
                          > #
                          >
                          > What I don't find so "nice" is to have to build an infinite loop only to
                          > break it.[/color]

                          checking if a logical expression is true by comparing it to True is bad
                          style, and comparing values using "is" is also bad style.

                          the correct way to write that if-statement is:

                          if final_condition :
                          break

                          and yes, the "infinite" while loop is a standard Python pattern. get
                          used to it.

                          </F>



                          Comment

                          • Konstantin Veretennicov

                            #14
                            Re: Loop until condition is true

                            On 6/21/05, Magnus Lycka <lycka@carmen.s e> wrote:[color=blue]
                            > I don't know anything about the Python compiler internals,
                            > but it doesn't seem very hard to identify simple literals following
                            > while and if, and to skip the runtime test. (Perhaps it's done
                            > already?)[/color]

                            True doesn't seem to be a literal, it is looked up by name and can be
                            rebound to, say, 0 anytime:
                            [color=blue][color=green][color=darkred]
                            >>> import dis
                            >>> o = compile('while True: pass', '<string>', 'exec')
                            >>> dis.dis(o)[/color][/color][/color]
                            1 0 SETUP_LOOP 12 (to 15)[color=blue][color=green]
                            >> 3 LOAD_NAME 0 (True)[/color][/color]
                            6 JUMP_IF_FALSE 4 (to 13)
                            9 POP_TOP
                            10 JUMP_ABSOLUTE 3
                            ...

                            OTOH,
                            [color=blue][color=green][color=darkred]
                            >>> p = compile('while 1: pass', '<string>', 'exec')
                            >>> dis.dis(p)[/color][/color][/color]
                            1 0 SETUP_LOOP 5 (to 8)[color=blue][color=green]
                            >> 3 JUMP_ABSOLUTE 3[/color][/color]
                            ...

                            - kv

                            Comment

                            • Magnus Lycka

                              #15
                              Re: Loop until condition is true

                              Konstantin Veretennicov wrote:[color=blue]
                              > On 6/21/05, Magnus Lycka <lycka@carmen.s e> wrote:
                              >[color=green]
                              >>I don't know anything about the Python compiler internals,
                              >>but it doesn't seem very hard to identify simple literals following
                              >>while and if, and to skip the runtime test. (Perhaps it's done
                              >>already?)[/color]
                              >
                              >
                              > True doesn't seem to be a literal, it is looked up by name and can be
                              > rebound to, say, 0 anytime:[/color]

                              Right. Silly me. Maybe in some future Python version, True and False
                              will be constants, like None is since Python 2.4.

                              Comment

                              Working...