how to finish a while loop...

Bruno Desthuilliers bruno.42.desthuilliers at
Wed Feb 20 11:02:56 CET 2008

icarus a écrit :
> Hi all, i'm new to python.  Learning on my own how to ask a user to
> finish a loop or not.
> For some reason, it behaves as infinite loop although I changed its
> condition.  Please tell me what I'm doing wrong. Thanks in advance.

Problem mostly solved, so I'll just comment a bit on the code:

> condition = True
> while ( condition ):

You don't need the parens here

while condition:

>         try:
>                 integer_one = int ( raw_input( "Please enter an
> integer: " ) )
>                 integer_two = int ( raw_input( "Please enter the
> second integer: " ) )
>                 division = integer_one / integer_two
>         except( ZeroDivisionError ):

You don't need (nor want) the parens here:

           except ZeroDivisionError:

>                 print "\nDivision by zero detected"
>         except( ValueError ):


Also, the user will have to start over (ie: re enter 2 integers) if it 
fails the second time.

>                 print "\nYou didn't enter an integer"
>         else:
>                 print "The result is", division
>                 answer = raw_input("Do you want to try again (yes or
> no)? ")
>                 if answer == 'yes':
>                         condition

This line is basically a noop. You don't need this part of the branch.

>                 elif answer == 'no':
>                         condition = False

This could be rewritten as:

                   if answer == 'no':
                           condition = False

which is a very verbose way to say:

                   condition = (answer != 'no')

> print "Good bye, you don't want to continue"

here's a possible rewrite:

class DecodeError(RuntimeError):

def nodecode(val):
    return val

def decodeint(val):
         return int(val)
     except ValueError:
         raise DecodeError("%s is not an integer" % val)

def decodeyesno(val):
         return YESNO[val.strip().lower()]
     except KeyError:
         raise DecodeError("please answer 'yes' or 'no'")

def read_input(prompt, decode=nodecode):
     while True:
         val = raw_input(prompt)
             return decode(val)
         except DecodeError, e:
             print e

def main():
     run = True
     while run:
         integer_one = read_input("Please enter an integer: ", decodeint)
         integer_two = read_input(
                            "Please enter the second integer: ",
             division = integer_one / integer_two
         except ZeroDivisionError:
             print "Division by zero detected"
             print "The result is", division
             run = read_input(
                     "Do you want to try again (yes or no)? ",

     print "Good bye, you don't want to continue"

if __name__ == '__main__':

More information about the Python-list mailing list