Python Forum
modulo and order of operations - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: modulo and order of operations (/thread-1365.html)



modulo and order of operations - freakbot - Dec-28-2016

I'm using 2.7.X
Working with the following:
print 100 - 25 * 3 % 4
When i run this i get 97 as the answer.

It seems like it I should be getting 6 with a 1 as remainder
-25 * 3 = -75
then 100-75 = 25
then 25/4=6 with 1 remainder

What is it that I'm missing in understanding this? Is there a page on the forum I have missed in my search that will explain this?
Thank you for any assistance


RE: modulo and order of operations - Hellerick - Dec-28-2016

25 * 3 = 75
75 % 4 = 3
100 - 3 = 97

Modulo has the same rank as * and /, so those operations are executed from left to right. And + or - go after them.


RE: modulo and order of operations - Mekire - Dec-28-2016

This page shows the precedence of all operations:
https://docs.python.org/2/reference/expressions.html#operator-precedence

Multiplication and modulo have the same precedence, so they are done in the order they are listed.
Subtraction of course has lower precedence so it is done last.
>>> 25 * 3
75
>>> 75 % 4
3
>>> 100 - 3
97
>>> 25 * 3 % 4
3
>>> 100 - 25 * 3 % 4
97



RE: modulo and order of operations - freakbot - Dec-28-2016

Awesome, Thank you. Big Grin
Knowing the order solves the issue


RE: modulo and order of operations - nilamo - Dec-28-2016

When there's so many things going on, you should probably either use parentheses, or split the operation over several lines. For those of us who don't have any desire to remember that modulus is the same order of precedence as division.