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?
Most programming languages adopt the convention that the modulo operator (denoted by % rather than mod ) occupies the same place in the order of operations as multiplication and division. Hence, it comes AFTER the operations in parentheses, but BEFORE addition and subtraction.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem. The modulo operator is considered an arithmetic operation, along with + , - , / , * , ** , // .
PEMDAS is P , E , MD , AS ; multiplication and division have the same precedence, and the same goes for addition and subtraction. When a division operator appears before multiplication, division goes first. The order Python operators are executed in is governed by the operator precedence, and follow the same rules.
The multiplication, modulus and division are evaluated first in left-to-right order (i.e., they associate from left to right) because they have higher precedence than addition and subtraction. The addition and subtraction are applied next.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With