0

This code does not, for some reason work. It works with the 'and' command but I'm not completely sure how to use 'or'. My current code:

if (response1 not in symbols or letters):
    print("You did something wrong")
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
  • See http://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true and http://stackoverflow.com/questions/15112125/if-x-or-y-or-z-blah – Jon Clements Mar 27 '14 at 10:42
  • 4
    Sometimes I wonder if it would've been better to use `&&` and `||` instead of `and` and `or`, just to make people realize the operators don't do the zillion things the English conjunctions do. – user2357112 Mar 27 '14 at 10:46

2 Answers2

4

The or in Python (and most programming languages for that matter) is not like the 'or' from spoken languages. When you say

if (response1 not in symbols or letters)

Python actually interprets it as

if ((response1 not in symbols) or (letters))

which is not what you want. So what you should actually be doing is:

if ((response1 not in symbols) and (response1 not in letters))
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
  • 1
    @user3468137: In addition to this answer you can also read about [Expressions summary documentation](http://docs.python.org/2/reference/expressions.html#expressions). Especially [Boolean Operations](http://docs.python.org/2/reference/expressions.html#boolean-operations), [Expressions evaluation order](http://docs.python.org/2/reference/expressions.html#evaluation-order) and [Operator Precedence](http://docs.python.org/2/reference/expressions.html#operator-precedence) – vaibhaw Mar 27 '14 at 11:22
1

or is a logical operator. If the part before or is true-ish, then that is returned, and if not, the second part is.

So here, either response1 not in symbols is True and then that is returned, or otherwise letters is returned. If there are things in letters then it is true-ish itself, and the if statement will consider it True.

You're looking for

if (response1 not in symbols) and (response1 not in letters):
    print("You did something wrong")
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79