[Tutor] How to make to exit the loop, while typing Enter

Adam adam.jtm30 at gmail.com
Tue Jan 3 19:38:24 CET 2006


Woops, forgot to reply-all.
---------- Forwarded message ----------
From: Adam <adam.jtm30 at gmail.com>
Date: 03-Jan-2006 15:48
Subject: Re: [Tutor] How to make to exit the loop, while typing Enter
To: John Joseph <jjk_saji at yahoo.com>


array = []
> m = 0
> print "Enter  to exit"
> m = int(raw_input("Enter the  Values for  The Array :
> "))
> array.append(m)
> print array
> while m != "":
>         m = int(raw_input("Enter the  Values for  The
> Array :  "))
>         array.append(m)
>         print array


The problem is that if a value is entered that can't be converted to an
integer type, like "" or a letter then an exception is raised. What you
could do is use a try, except.
while 1:
    try:
        m = int(raw_input("Enter the  Values for  The Array: "))
        array.append(m)
        print array
    except ValueError:
        sys.exit()

alternatively you could do something like this:
 m=raw_input("Enter the  Values for  The Array: ")
if m == "": sys.exit()
try:
    int(m)
    array.append(m)
    print array
except ValueError:
    print "Only integer values can be entered into the array, or press the
enter key to exit."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060103/5a8ecf5e/attachment.html 


More information about the Tutor mailing list