How does the order of operations work in Python?

How does the order of operations work in Python?

I’m trying to solve an equation like this:

10 - 7 // 2 * 3 + 1

I expect to get the answer 8 using the PEMDAS rule:

  1. First, solve 2 * 3 = 6, so the equation becomes 10 - 7 // 6 + 1.
  2. Then, 7 // 6 = 1, so the equation becomes 10 - 1 + 1.
  3. Finally, 10 - 1 + 1 = 8.

But when I try it in Python, I get the answer 2. Why is this happening?

It seems like Python is following a different order of operations:

  1. 7 // 2 = 3, so the equation becomes 10 - 3 * 3 + 1.
  2. Then, 3 * 3 = 9, so the equation becomes 10 - 9 + 1.
  3. Finally, 10 - 9 + 1 = 2.

Can someone explain how Python order of operations works in this case?

Python follows standard operator precedence, but it’s essential to understand how operators are evaluated. For example, the floor division operator // and multiplication * have higher precedence than addition + and subtraction -.

This is why your equation was evaluated as 10 - (7 // 2) * 3 + 1, where 7 // 2 = 3 and then 3 * 3 = 9.

Thus, the order of operations is:

First, floor division: 7 // 2 = 3 Then multiplication: 3 * 3 = 9

Finally, addition and subtraction: 10 - 9 + 1 = 2.

To achieve the expected result according to PEMDAS, you can use parentheses to explicitly control the order.

For example, adding parentheses around the division and multiplication would make sure that 7 // 2 happens before multiplication:

result = 10 - (7 // 2 * 3) + 1 # Output: 8

This ensures that the floor division and multiplication are evaluated first, as per your intended order.

Python 3 uses true division (/) and floor division (//), which can lead to different results depending on which operator you use.

If you intended the result to be a floating-point division, you could use / instead of //:

result = 10 - (7 / 2 * 3) + 1 # Output: 8.5

This ensures floating-point division happens rather than floor division, which changes the evaluation order.