Python Order of Operations: Unary Negation Explained

  • Context: Python 
  • Thread starter Thread starter Mr Davis 97
  • Start date Start date
  • Tags Tags
    Operations
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
8 replies · 2K views
Mr Davis 97
Messages
1,461
Reaction score
44
I have the following table for order of operations in Python. It all makes sense except for the unary operation negation. What does it mean that the order of precedence is from right to left? Can I have an example?Symbols - Operator - Type Order of precedence

( ) Parentheses Highest

- Unary (from right to left)

*, /, //, % Multiplicative (from left to right)

+, - Additive (from left to right)
 
Physics news on Phys.org
!false
means: false > not
which means true.

!false
means false > not > not
which means false
 
Mr Davis 97 said:
I have the following table for order of operations in Python. It all makes sense except for the unary operation negation. What does it mean that the order of precedence is from right to left? Can I have an example?Symbols - Operator - Type Order of precedence

( ) Parentheses Highest

- Unary (from right to left)

*, /, //, % Multiplicative (from left to right)

+, - Additive (from left to right)
The left to right or right to left business describes how an expression using a given operator associates, and is not related to the order of precedence. For example, the + additive operator associates left to right. This means that a + b + c is treated as if it had been written (a + b) + c.

The ~ bitwise "not"operator associates right to left. This means that the expression ~~x is evaluated as if it were written ~(~x). I didn't use the unary - for an example, because -- is a different operator (decrement).
 
DaveC426913 said:
!false
means: false > not
which means true.
Not in python. There is no ! operator in python. The correct operator in python is no. And it doesn't mean false > not (whatever that means). not false in python means exactly what a naive reader would think it means, which is true.

!false
means false > not > not
which means false
Not in python. Here, a>b>c means exactly what a physicist or mathematician would read that to mean, as opposed to a computer scientist. In python, a>b>c means that b is between c (lower bound) and a (upper bound), exclusive of c and a.

Aside: Using tokens such as not in a non-reserved context is generally perceived as a bad thing in python. (A very bad thing; you will get yourself in deep trouble if you name a variable not or len.)
 
Last edited:
D H said:
Not in python. There is no ! operator in python.
Yeah. I prolly should have looked up the syntax of python before posting. :oops:
 
I see what you did there!