[Tutor] Input checking [letters or numbers]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Dec 23 20:16:35 CET 2005


> x = raw_input("x : ")
> if x.isdigit(): # ensure input is a number
>    y = int(x) # convert to integer
> else:
>    print 'Boo"


Hello Bob and Panagiotis,

It might be good to make this number-reading thing a function, just to
make it easier to reuse (and test!) it.  Let's call this input_number()
for the moment.

#######################################################
def input_number(prompt):
    """Reads an integer from the next line of input."""
    while 1:
        x = raw_input(prompt)
        if x.isdigit():
            return int(x)
        else:
            print 'Boo'
#######################################################


Does this work?  Let's try it informally:

######
>>> input_number('number please: ')
number please: 1
1
>>> input_number('number please: ')
number please: 1234
1234
>>> input_number('number please: ')
number please: 1st
Boo
number please: 74
74
>>>
######

I added one more behavior so that input_number continues to ask until it's
satisified by a number.  Hope this helps!



More information about the Tutor mailing list