[Tutor] strange behavior in program

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Jun 12 17:47:21 EDT 2004


> while again:
>     original = raw_input("Please enter numbers or text to be
converted. ")

The following for loop is not controlled by again, it will process
every letter regardless, as you've seen. If you want the loop to
stop at an arbitrary point rather than process every letter you
need another while loop:

>     for char in original:

      index = 0
      while index < len(original) and again:
          char = original[index]
>         try:
>             int(original)
>         except TypeError:
>             convertxt()
>         except ValueError:
>             convertxt()
>         else:
>             if char in number:
>                 convertnum()
>         again = raw_input("Would you like to convert more text or
numbers [y/n]? ")
>         if again in 'Yy':
>             again = True
>         elif again in 'Nn':
>             again = False

An alternative approach uses break like so:

       for char in original:
          if not again: break
          # otherwise continue as before

I'm not a big fan of break because it goes against the principles
of structured programming and can lead to obscure bugs. But in
this case it seems to me to be the cleanest solution so I'd go
with break.

Alan G.




More information about the Tutor mailing list