[Tutor] Input checking [letters or numbers]

Panagiotis Atmatzidis p.atmatzidis at gmail.com
Fri Dec 23 20:25:12 CET 2005


Hello Dany :-)

On 12/23/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> > 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!

Yes, it really helps a lot. Now I can proceed with my script!!

Thank you for the reply,

Best Regards,

Panagiotis


More information about the Tutor mailing list