2.7. Order of operations¶
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. 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 4, and(1+1)**(5-2)
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
2**1+1
is 3, not 4, and3*1**3
is 3, not 27.Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
2*3-1
is 5, not 4, and6+4/2
is 8, not 5.Operators with the same precedence are evaluated from left to right. So the expression
5-3-1
is 1, not 3, because the5-3
happens first and then1
is subtracted from 2.
- 18
- Try running the code in your python interpreter.
- -2
- 4 + -2 * 3 is -2. First -2 is multiplied by 3 then 4 is added.
- 6
- Which order will the operators run?
- 10
- Make sure that you are using a negative 2, not positive.
csp-10-2-2: What is printed from the following codeblock?
result = 4 + -2 * 3
print(result)
- 18
- Try running the code in your python interpreter.
- -2
- Which order will the operators run?
- 6
- With parentheses, (4 + -2) * 3 is 6.
- 10
- Make sure that you are using a negative 2, not positive.
csp-10-2-3: What is printed from the following codeblock?
result = (4 + -2) * 3
print(result)
Try running the code below as is, then add parentheses around 4 + -2
to see how the order of operations changes.
When in doubt, always put parentheses in your expressions to make sure the computations are performed in the order you intend.
Put these code blocks in the oder that they would run using the order of operations.