[Tutor] validation

Alan Gauld alan.gauld at btinternet.com
Mon Aug 27 12:54:10 CEST 2007


"Michael" <python at mrfab.info> wrote

> to check and make sure that an integer is entered and the program 
> not
> crashing when a naughty user enters a character instead.

John F has already pointed you to the use of try/except for this,
however...

> 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,

The easiest way is to compare to another type:

x = 42
if type(x) == type(int()):

or even

if type(x) == type(2):

Or you can use the types module:

if type(x) == types.IntType

But for your purposes the Python idiom of its 'better to ask
forgiveness than permission' applies.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list