What's wrong with order for not() in python?

390 views Asked by At

What's wrong with using not() in python?. I tried this

    In [1]: not(1) + 1
    Out[1]: False

And it worked fine. But after readjusting it,

    In [2]: 1 + not(1)
    Out[2]: SyntaxError: invalid syntax

It gives an error. How does the order matters?

1

There are 1 answers

5
Martijn Pieters On BEST ANSWER

not is a unary operator, not a function, so please don't use the (..) call notation on it. The parentheses are ignored when parsing the expression and not(1) + 1 is the same thing as not 1 + 1.

Due to precedence rules Python tries to parse the second expression as:

1 (+ not) 1

which is invalid syntax. If you really must use not after +, use parentheses:

1 + (not 1)

For the same reasons, not 1 + 1 first calculates 1 + 1, then applies not to the result.