Trying To Catch Invalid User Input

Victor Subervi victorsubervi at gmail.com
Sun Aug 23 12:27:48 EDT 2009


Really slick! Thanks!
V

On Sun, Aug 23, 2009 at 11:08 AM, Albert Hopkins <marduk at letterboxes.org>wrote:

> On Sun, 2009-08-23 at 16:36 +0100, MRAB wrote:
> > Victor Subervi wrote:
> > > Hi;
> > > I have the following:
> > >
> > > style = raw_input('What style is this? (1 = short, 2 = long): ')
> > > flag = 0
> > > while flag == 0:
> > >   if (style != 1) or (style != 2):
> > >     style = raw_input('There was a mistake. What style is this? (1 =
> > > short, 2 = long): ')
> > >   else:
> > >     flag = 1
> > >
> > > I would think this would catch errors and permit valid values, but it
> > > doesn't. If I enter an erroneous value the first time, and the second
> > > time a good value, it doesn't break the loop. Why?
> > >
> > This is wrong:
> >
> >      (style != 1) or (style != 2)
> >
> > For example, if style is 1 (which should be a valid value):
> >
> >      (style != 1) or (style != 2)
> >   => (1     != 1) or (1     != 2)
> >   => False        or True
> >   => True
> >
> > What you mean is:
> >
> >      (style != 1) and (style != 2)
>
> Or (perhaps) better:
>
> VALID_STYLES = {1: 'short', 2: 'long'}
>
> style = None
> while style not in VALID_STYLES:
>    style = raw_input('What style is this? %s: ' %
>        str(VALID_STYLES).replace(':', ' ='))
>
>    # also, raw_input() returns a string
>    try:
>        style = int(style)
>    except ValueError:
>        pass
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090823/2620162a/attachment-0001.html>


More information about the Python-list mailing list