srtring to int question

Matthew Dixon Cowles matt at mondoinfo.com
Sat Aug 12 22:20:52 EDT 2000


In article <slrn8pbuah.1t3.warlock at gargoyle.myth>, warlock at eskimo.com
(Jim Richardson) wrote:

> For various reasons, I have written a small bit of python code to
> take a 1-3 julian day, and return the day-month form. It works
> ok mostly (available at http://www.eskimo.com/~warlock/freesoft/julian_py.tgz)
>  OK, the question, I use raw_input to poll for the julian day, and 
> then convert to int via int, but how do I check that the value from raw_input
> is "intable"? that is, it works fine if I pass a number, but if I type in
> non-numerical characters, [a-zA-Z!@# etc] then the code errors on the
> int() function. Any pointers? thanks

Jim,
Python's exceptions are just what you want for this sort of purpose.
You probably want something like this:

myInput=raw_input("Enter an integer: ")
try:
  myInt=int(myInput)
except ValueError:
  print "Shame on you, that wasn't an integer"
else:
  print "Thank you"

More information is at:

http://www.python.org/doc/current/tut/node10.html

Regards,
Matt



More information about the Python-list mailing list