Trying To Catch Invalid User Input

Gary Herron gherron at islandtraining.com
Sun Aug 23 17:37:26 CEST 2009


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?
> TIA,
> Victor
First, raw_input will not return an integer, but rather characters, so 
the value of style will never be 1 or 2, but rather '1', or '2'.  

But even if you make your comparisons against  '1' and '2', this will 
not work since you've also made a simple logic error.  The conditional
  if (style != '1') or (style != '2'):
will always be True no matter what value  style has.  For instance
if style is '1', then the conditional evaluates like
  (False) or (True)
which evaluates to True. 

You want one of the following:
  if (style != '1') and (style != '2'):
or
  if not (style == '1' or style == '2'):
or
  if style == '1' or style == '2':
    flag = 1
  ...
or
  if style in ['1','2']:
    flag = 1
  ...
or better yet dispense with flag altogether
  while style not in ['1','2']:
    style = raw_input('There was a mistake ...

Gary Herron







More information about the Python-list mailing list