[Tutor] Input checking [letters or numbers]

bob bgailer at alum.rpi.edu
Fri Dec 23 19:45:05 CET 2005


At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>Hello,
>
>Can someone provide me with an error checking example about an x
>variable that needs to be number only? I used something like:
>
>  def useridf():
>      print ""
>      print "WARNING: If you don't understand why this must be unique,
>exit and read the manual."

You ask the user to exit but you don't tell him how to do that!

>      print ""
>      userid = input("x : ")
>
>I know that "input" accepts only numbers

How did you "know" that? Try this:
print input("x ; ")
and enter "Hello world"

Truth is input() "accepts" anything and attempts to evaluate it as a 
Python expression. If that fails it raises an exception.

You should use raw_input() instead. This takes any input and returns 
it as a character string.
x = raw_input("x : ")
if x.isdigit(): # ensure input is a number
   y = int(x) # convert to integer
else:
   print 'Boo"

>, but I don't want the program
>to break if someone puts other chars in it. I want to, print "Only
>numbers are accepted." which is easy. But still I can't understand how
>to do the check using if/elif/else statements.



More information about the Tutor mailing list