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

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

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

      

And everything worked out great. But after adjusting it

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

      

This gives an error. How does order matter?

+3


source to share


1 answer


not

is a unary operator , not a function, so please do not use a call notation on it (..)

. The parentheses are ignored when the expression is ignored, but not(1) + 1

is the same 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

, it calculates first 1 + 1

, then applies not

to the result.

+8


source







All Articles