[Tutor] validation
John Fouhy
john at fouhy.net
Mon Aug 27 12:17:18 CEST 2007
On 27/08/07, Michael <python at mrfab.info> wrote:
> I am fairly new to Python and I wish to validate input. Such as wanting
> to check and make sure that an integer is entered and the program not
> crashing when a naughty user enters a character instead. I have been
> trying to use the Type() function but I cannot work out how to check the
> return value? Caomparing it to 'int' or 'str' isn't working, or should I
> be using the isinstance property? I want to use raw_input and check that
> it is a number. Can someone point me in the right direction?
Hi Michael,
raw_input() will give you a string. Python does not do automatic type
conversions, like some languages do. To convert string to int, you
can use int(). e.g.:
user_input = raw_input()
num = int(user_input)
If you call int() on something that is not a valid integer string,
this will throw an exception -- TypeError, I think. So the pythonic
way to check is to catch the exception:
while True:
user_input = raw_input()
try:
num = int(user_input)
break
except TypeError:
print 'Oops, try again!'
HTH!
--
John.
More information about the Tutor
mailing list