Today, I noticed that not True + 5 is syntactically valid but 5 + not True isn’t.
The syntax error points to the first character of not, as if the operator couldn’t be used here. However, 5 + (not True) works, which leads me to believe it is a parser issue.
Are there any reasons for this error?
- Is it a design decision taken by the language?
- Is it is a parser error, or a behaviour not defined by the language’s rules?
I couldn’t find any ressources concerning this case.
>Solution :
It’s an operator precedence issue; see e.g. this table in the documentation. + binds more tightly than not, so this:
not True + 5
Is equivalent to:
not (True + 5)
And True evaluates as 1 in this case (so you get True + 5 == 6, and not 6 == False). On the other hand:
5 + not True
Is:
(5 + not) True
Which doesn’t make any sense. You would need to explicitly write:
5 + (not True)
(Which would equal 5, since not True is False and False evaluates to 0.)