Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority of the logical statements NOT AND & OR in python

As far as I know, in C & C++, the priority sequence for NOT AND & OR is NOT>AND>OR. But this doesn't seem to work in a similar way in Python. I tried searching for it in the Python documentation and failed (Guess I'm a little impatient.). Can someone clear this up for me?

like image 745
Akshar Gupta Avatar asked May 21 '13 20:05

Akshar Gupta


People also ask

What is the priority of logical operator NOT and and or?

Logical operators have operator precedence the same as other operators (relational, arithmetic, etc.). The highest precedence belongs to not , followed by and , and finally by or .

Which comes first and or or?

1 Expert AnswerThe AND (&&) does indeed come first, followed by the OR (||). Next, the OR statement is evaluated against the outcome of the previous AND.

What are the 3 logical operators?

There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English.


2 Answers

It's NOT, AND, OR, from highest to lowest according to the documentation on Operator precedence

Here is the complete precedence table, lowest precedence to highest. A row has the same precedence and chains from left to right

 0. :=  1. lambda  2. if – else  3. or  4. and  5. not x  6. in, not in, is, is not, <, <=, >, >=, !=, ==  7. |  8. ^  9. &  10. <<, >>  11. +, -  12. *, @, /, //, %  13. +x, -x, ~x  14. **  14. await x  15. x[index], x[index:index], x(arguments...), x.attribute  16. (expressions...), [expressions...], {key: value...}, {expressions...} 
like image 73
Kyle Heuton Avatar answered Sep 19 '22 22:09

Kyle Heuton


You can do the following test to figure out the precedence of and and or.

First, try 0 and 0 or 1 in python console

If or binds first, then we would expect 0 as output.

In my console, 1 is the output. It means and either binds first or equal to or (maybe expressions are evaluated from left to right).

Then try 1 or 0 and 0.

If or and and bind equally with the built-in left to right evaluation order, then we should get 0 as output.

In my console, 1 is the output. Then we can conclude that and has higher priority than or.

like image 21
nos Avatar answered Sep 19 '22 22:09

nos