dopatraman
dopatraman

Reputation: 13908

SyntaxError thrown in if statement with multiple boolean operators

This is my code:

if mode not "w" or mode not "r+":
    # do stuff

This results in the following error:

SyntaxError: invalid syntax

Does anyone know what I'm doing wrong?

Upvotes: 1

Views: 81

Answers (3)

bnjmn
bnjmn

Reputation: 4584

Try this:

if not mode == "w" or not mode == "r+":
    ...

This should prevent you from seeing the SyntaxError. However, as these are common values for opening file objects to be writable, you could also try writing to the file and catch the IOError. Something like this,

f = open('blah', 'r')
try:
    f.write("Something amazing")
except IOError:
    # do something to read-only file

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1125088

not is not a comparison operator; it is a unary boolean operator, which means it only takes one argument.

Perhaps you wanted !=, not equals?

if mode != "w" and mode != "r+":

I also replaced or with and, because if the mode is equal to 'w' it'll also not be equal to 'r+'. All those negatives make it hard enough to grok, you could use:

if not (mode == 'w' or mode == 'r+'):

if that's easier to understand, logically speaking.

You can also combine the test into one by using a tuple and a negative membership test, not in:

if mode not in ('w', 'r+'):

which is a lot easier to read and understand.

Upvotes: 5

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391724

You can't compare items with this syntax:

a not b

You need to compare them with this syntax:

a != b

So rewrite your if-statement to this:

if mode != "w" or mode != "r+":
    # do stuff

Now, having said that, that is purely syntax-based changes.

The problem is, this if-statement doesn't make sense, so even if you do the above change, it will certainly not do what you want it to do.

Consider this: What if mode is "w"? Then it will not be "r+", and vice versa. In other words, every value will be different from both, or at least one of them.

I suspect you need and instead of or:

if mode != "w" and mode != "r+":
    # do stuff

Upvotes: 2

Related Questions