[Tutor] Input checking [letters or numbers]

bob bgailer at alum.rpi.edu
Fri Dec 23 21:42:07 CET 2005


At 11:28 AM 12/23/2005, Panagiotis Atmatzidis wrote:
>On 12/23/05, Panagiotis Atmatzidis <p.atmatzidis at gmail.com> wrote:
> > Hello Dany :-)
> >
> > On 12/23/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>[...]
> > >
> > >
> > > 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'
> > > #######################################################
>[...]
> > > 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!!
>[...]
>
>Another newbe question! I use "while True: " to evaluate an 
>expression, I see that you used while 1: .. what's the diffrence if any?!

In this case, no difference. True and False are Python boolean 
constants, and also a subset of integer. So one may print True + 1 and see 2.

Conditional statements (while, if, elif) and the if clause of list 
comprehensions and generator expressions expect an expression that 
will be treated as True if not empty and False if empty. From the 
L:angRef: "In the context of Boolean operations, and also when 
expressions are used by control flow statements, the following values 
are interpreted as false: None, numeric zero of all types, empty 
sequences (strings, tuples and lists), and empty mappings 
(dictionaries). All other values are interpreted as true."



More information about the Tutor mailing list