Practice With Operator Precedence
Now, we will consider order precedence when operations are phrased within the Python programming language. Before running this set of instructions in the run window, try to predict the value each variable will contain.
a=3 b=4 c=1 d=5 e=3 f=a+b-c*d+e/d g=a+b-c*(d+e)/d h=a+(b-c)*d+e/d i=(a+b-c)*d+e/d
You may use the print statement to verify your answer.
It is important to note that // and % are considered division operations and, because of that, have precedence equal to * and /. Try to predict the value of each variable in these commands:
v=2 w=3 x=4 y=19 z=23 a=v**v//x%x+y%w*z//x b=v**(v//x)%x+y%(w*z)//x
Again, you should use insert some print commands to verify your answer.
A useful guiding principle when writing code is: if the order precedence is not clear to you by looking at the expression, use parentheses to make things obvious, since parentheses always take the highest precedence.
When an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1)is
8. You can also use parentheses to make an expression easier to read, as in
(minute * 100) / 60, even if it doesn't change the result.
- Exponentiation has the next highest precedence, so
1 + 2**3is
2 * 3**2is
- Multiplication and Division have higher precedence than Addition and Subtraction. So
- Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression
degrees / 2 * pi, the division happens first and the result is multiplied by
pi. To divide by 2π, you can use parentheses or write
degrees / 2 / pi.
Source: Allen B. Downey, http://greenteapress.com/thinkpython2/html/thinkpython2003.html#sec20
This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.