[Tutor] iterate problem

Isaac Isaac@compuserve.com
Sat, 15 Jul 2000 21:42:12 -0700


Daniel Yoo wrote:

>
> On Sun, 16 Jul 2000, David Jansen wrote:
>
> > a number of times). Removing the first > from the beginning of a line is no
> > problem but I seem to enter an endless loop when I attempt to iterate over
> > the line to get rid of second and third >'s if they exist.  The problem line
> > is obviously the while line in strip() but I can't figure out what is wrong
> > with it.
>
> Ah!  You're not going to like this one: it's the spaces in your test file.
> For example, take a look at what happens in this line:
>
> > > >The citrus soda 7-UP was created in 1929; "7" was selected because the
>
> If you look at your terminating condition:
>
> > ____while (len(input) > 0) and (input[0] not in alphas):
>
> you'll see that after your loop cuts off the first '>' character, 'input'
> gets stuck with a leading space in front.  After that, the loop goes
> infinite since ' ' isn't alphanumeric, and nothing in the body's loop
> deals with it.
>
> ###
> def spoiler_alert:
>    """By the way, a simpler way to state your condition and avoid the
>       infinite loop is:"""
>
>     while (len(input) > 0) and (input[0] == '<'):
>       input = input[1:]

Good one.  And if you want to deal with the '> > ' sitch, you could add

while (len(input) > 0) and (input[0] == '>'):
    if input[1] == ' ':
        input = input[2:]
    else:
        input = input[1:]

You do run the risk of deleting a desired blank at the beginning of the line this
way, but I'm sure you could work around that.

Another option, if the "in alphas" test is anticipating further analysis and
editing within the loop, is to put a break in an else clause.  eg. something like:

     while (len(input) > 0) and (input[0] not in alphas):
          if input[0] == ">":
               input = input[1:]
          elif input[0] == "!":
              input = "(please don't yell - " + input[1:]   # or whatever
          elif (etc.)
          else:
               break