[Tutor] Input checking [letters or numbers]

Kent Johnson kent37 at tds.net
Fri Dec 23 20:38:40 CET 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."
>      print ""
>      userid = input("x : ")
> 
> I know that "input" accepts only numbers, 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.

Another way to do this is to use raw_input() to get the input as a 
string, then just try to convert it to an int and catch any exception. 
This also works well encapsulated into a function:

def getInt(prompt):
   while 1:
     s = raw_input(prompt)
     try:
       return int(s)
     except ValueError:
       print 'Only numbers are accepted'

This approach will accept negative numbers as well as positive:

  >>> def getInt(prompt):
  ...   while 1:
  ...     s = raw_input(prompt)
  ...     try:
  ...       return int(s)
  ...     except ValueError:
  ...       print 'Only numbers are accepted'
  ...
  >>> getInt('x: ')
x: ae
Only numbers are accepted
x: -4
-4

Kent



More information about the Tutor mailing list