[Tutor] Re: Checking for int only
Andrei
project5 at redrival.net
Mon Jun 28 15:13:30 EDT 2004
K J wrote on Mon, 28 Jun 2004 15:07:44 -0400:
> How do you test for something to make sure that it is an int and not anything else
> so that when you ask them to enter a number they can only enter a number and
> not any other character.
Use try-except:
while True:
number = raw_input('Integer: ')
try:
number = int(number) # will fail if the input is non-numerical
break # stop endless loop
except: # int() failed -> not an integer
print ' That was not an integer.'
Above is assuming that you mean 'integer' when you write 'number'. If you
mean to include floats, try float() instead of int().
--
Yours,
Andrei
=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list