Trying To Catch Invalid User Input
Albert Hopkins
marduk at letterboxes.org
Sun Aug 23 12:08:02 EDT 2009
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
More information about the Python-list
mailing list