Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 607
dartdog Avatar asked Jan 18 '11 21:01

dartdog


People also ask

Where is modulo in order of operations?

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.

How do you do modulo operations in Python?

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 + , - , / , * , ** , // .

Which is the correct order for order of operations in Python?

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.

What comes first addition or modulo?

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.


2 Answers

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.

like image 148
Sven Marnach Avatar answered Nov 13 '22 08:11

Sven Marnach


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.

like image 44
chauncey Avatar answered Nov 13 '22 08:11

chauncey