[Tutor] types

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 28 Feb 2002 19:27:09 +0100


On  0, Ron <clickron@webtv.net> wrote:
> 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.

Firstly, you need to use raw_input instead of input - it returns the string
the user typed, and doesn't try to convert it itself. This is almost always
better (the user can type arbitrary Python commands into the input() prompt!)

Then, we put it in a loop, that continues until we break out of it when the
integer was entered correctly.

And you need to catch the error with a try: except: block.

It becomes something like:


while 1:
   s = raw_input("Enter a number: ")
   try:
      i = int(s)
   except ValueError:
      # Do this in case of an error
      print "Please enter a legal integer."
   else:
      # Do this if there was no error.
      break # End loop
      
print "You entered", i

This sort of thing takes 1 line, until the moment you start thinking about
the real world, then it suddenly takes around 10...

-- 
Remco Gerlich