Modulo and order of operation in Python

25,546

Solution 1

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.

Solution 2

Multiplication >> mod >> subtraction

In [3]: 25 * 3
Out[3]: 75

In [4]: 75 % 4
Out[4]: 3

In [5]: 100 - 3
Out[5]: 97

Multiplication and modulo operator have the same precedence, so you evaluate from left to right for this example.

Solution 3

I figured out the answer to your second question because it was bugging me too--Zac's response is close, but the loss of the result of 1/4 is because of Python 2.X is truncating integer division results. So it's evaluating the modulo operation first, then the division (which since it isn't float, is returned as 0.

3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
3 + 2 + 1 - 5 + (0) - (0) + 6 
6 - 5 + 6
1 + 6
7
Share:
25,546
dartdog
Author by

dartdog

Open Software professional Developing Open SoftWare Co, oswco

Updated on July 29, 2022

Comments

  • dartdog
    dartdog over 1 year

    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?

  • Sven Marnach
    Sven Marnach over 13 years
    It's not only a question of what appears first. For example 2**3**4 == 2**(3**4), because the associativity of ** is right to left.
  • Sven Marnach
    Sven Marnach over 13 years
    Not everything with the same precedence is evaluated from left to right -- e.g. 2**3**4 == 2**(3**4) is evaluated from right to left.
  • dartdog
    dartdog over 13 years
    Thanks to all this, your answer and the ones that follow are very helpful, even the references, and I have most don't really make this clear, and the whole modulo concept is a bit alien to me..although I get it have never had the use case.(for modulo that is..)
  • Felipe Alvarez
    Felipe Alvarez over 11 years
    a standard wall clock is "modulo 60" because once you get to 59 minutes, and add 1 minute, you get 0 (== 60)
  • Jacqlyn
    Jacqlyn over 10 years
    The modulo is just the remainder of division. Knowing when to us it can be tricky, but the concept is rooted in basic math.