Trying To Catch Invalid User Input

MRAB python at mrabarnett.plus.com
Sun Aug 23 11:36:10 EDT 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?
> 
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)



More information about the Python-list mailing list