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?
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.
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
Here's how it goes:
'*' and '%' have the same precendence, so evaluate those from left to right.
- 25*3 = 75
- 75 % 4 = 3 (4*18 = 72; remainder is 3)
- 100 - 3 = 97
Q.E.D.
Original problem: 100 - 25 * 3 % 4
Actually, evaluating 25 * 3
and taking 75% of 4 is incorrect, and happened to work out conveniently for this problem.
What the % in python actually is is a modulus operator where x % y gives the remainder of x / y
. In this case, what happened was that 75 / 4
is 18, with a remainder of 3, which is why 100 - 3 = 97
.
Do not try to multiply the percentages, it's a common mistake.
In the second exampe, %has same order as * so we get 3+2+1-5+4%2-1/4+6= 3+2+1-5+(4%2)-(1/4)+6=1+(4%2)-(1/4)+6 =1+0-(1/4)+6=1-(1/4)+6=0.75+6=6.75 and that is what it says when I try it on the console, so whatever you did you must have done something to round it.
Mathematics isn't my strong point, so yes this question got me as well, for a moment. But hope you find this useful.
75 divided by 4 is 18.75
18 multiplied by 4 is 72 (leaving 3 remaining from the 75)
The calculation given is 100-25*3%4 with an answer of 97. Now this is how I would get it using PEMDAS as he speaks of in the question section:
#!/bin/python
A = 100
B = 25
C = 3
D = 4
E = B*C # 75
F = E%D # 3
G = A-F # 97
print("B * C ="), E
print("E % D ="), F
print("A - F ="), G
I think you have to treat modulo (%) as a division,
Python evaluates % after * but before + or _ .
So,
(100 - 25 * 3 % 4)
(100 - 75 % 4)
(100 - 3)
(97)
精彩评论