dartdog dartdog - 5 months ago 8
Python Question

Modulo and order of operation in Python

In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

100 - 25 * 3 % 4


the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ??? but anyhow not 97 I don't think...

A similar example is
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
which yields 7

In what order are the operations done?

Answer

For the first example: * and % take precedence over -, so we first evaluate 25 * 3 % 4. * and % have the same priority and associativity from left to right, so we evaluate from left to right, starting with 25 * 3. This yields 75. Now we evaluate 75 % 4, yielding 3. Finally, 100 - 3 is 97.