Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of operations Incorrect?

I'm using the Python 3.5.2 shell. I am confused about why this works as it does?

5 > 5**2
False
5 > 5**2 == False
False
(5 > 5**2) == False
True

The order of the operations defines that ** is executed before > which is before == so it should work.

like image 879
Steven Waterman Avatar asked Oct 21 '16 13:10

Steven Waterman


People also ask

What is the correct answer to 3 3x6 2?

Question: 3 – 3 x 6 + 2. Multiplication first: 3 – 18 + 2. Left to right: -15 + 2 (or Addition first: 3 – 16) Answer: -13.

What will happen if we don't follow order of operations?

Formulas for actual calculations in science and finance would be quite worthless without a set order of operations, and it would be challenging to determine whether your response on a math test was correct. The order of operations in mathematics helps determine the right value for an equation.

Does order of operations always apply?

Yes, always use the order of operations to simplify expressions. If there are no parentheses, then skip that step and move on to the next one. The same applies for any other missing operation.


1 Answers

Interesting question! The reason for this behavior is that all the comparison operators in Python have equal precedence and can be chained.

So your second comparison is equivalent to

5 > 25 and 25 == False

which of course evaluates to False. But I agree that in this case, it's not very intuitive.

like image 99
dorian Avatar answered Sep 20 '22 17:09

dorian