Python Forum

Full Version: modulo and order of operations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
This page shows the precedence of all operations:
https://docs.python.org/2/reference/expr...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
Awesome, Thank you. Big Grin
Knowing the order solves the issue
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.