-1

I want to list several vairables in a function so they will all be detected:

    if how != 'no'or'yes':
        print"That is not a valid answer"

so i want the if how != to read no and yes but when i run only no is detected

Stratmoss
  • 19
  • 6
  • no i need both yes and no to be detected and it does n't always evaluate to true – Stratmoss May 11 '14 at 19:14
  • See http://stackoverflow.com/questions/15112125/if-x-or-y-or-z-blah ... Specifically `if 1 in (x, y, z):` and you can rework that – Liam McInroy May 11 '14 at 19:14
  • Minor note: 'or' is not a function, it's a logical operator. See http://www.tutorialspoint.com/python/logical_operators_example.htm. – jarmod May 11 '14 at 19:33

1 Answers1

0

in your if condition:

if how != 'no' or 'yes':

you're making a wrong assessment, it's that python will understand that the value of how is either no or yes, like you would do in a natural language.

But what you're actually testing is whether how is different from no and whether yes is different from None:

if how != 'no' or 'yes' != None:

and the latter will always valuate to true.

The correct way to express your logic would be:

if how != 'no' or how != 'yes'

to be a bit more pythonic:

if not how == 'no' or not how == 'yes'

and the totally pythonic solution:

if how not in ('yes', 'no')
zmo
  • 24,463
  • 4
  • 54
  • 90
  • I would argue that `not how == 'yes'` is *not* "a bit more pythonic" of a way of writing the clearly defined inequality operator `!=`. Is `not x < 5` as obvious (or a bit more Pythonic) as `x >= 5`? Plus - some weird things might happen with precedence... – Jon Clements May 11 '14 at 19:19
  • Minor error: if how != 'no' or how != 'yes' will always evaluate to true so that should be 'and' rather than 'or' and should read as follows: if how != 'no' and how != 'yes'. – jarmod May 11 '14 at 19:20
  • if `how = 'perhaps', `how` will be different from `yes` and `no`. Don't be so binary! :-) – zmo May 11 '14 at 19:22
  • 1
    @zmo `if random.choice([True, False]):` is all everybody needs, right? – Jon Clements May 11 '14 at 19:23
  • @JonClements That's a whole interpretation of the expliciteness of such expression. I consider that what's pythonic is the readability, and when you read out loud: `if how is not 'yes' or how is not 'no'` is more explicit than operators. Though I did not use the `is` operator, because its behavior on strings is an exception ;-) – zmo May 11 '14 at 19:25