[Tutor] types

Gregor Lingl glingl@aon.at
Thu, 28 Feb 2002 21:43:53 +0100


You arrive at something simple if you use
raw_input() which asks for a string and then
try to convert to an integer and catch the error
if this doesn't work, asking again for another input:

def askForInteger(prompt):
    answer = raw_input(prompt)
    while type(answer)!=type(0):
        try:
            answer = int(answer)
        except:
            answer = raw_input("Enter an integer: ")
    return answer

Regards
Gregor

----- Original Message ----- 
From: "Ron" <clickron@webtv.net>
To: <tutor@python.org>
Sent: Thursday, February 28, 2002 7:17 PM
Subject: [Tutor] types


> I want to ask for a integer using something like number = input("Give me
> a number'), but if a string is accidentally put in I don't want it to
> throw an error message. I'd like it to say something like "Enter a
> number, try again."  I'm sure it's something simple and I'm just not
> seeing it. Appreciate any help out there.
> 
> Ron
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>