Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is logical not after an addition syntactically invalid?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading