Opening the book…
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)is4, and(1+1)**(5-2)is8. 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**3is9, not27, and2 * 3**2is18, not36. - Multiplication and Division have higher precedence than Addition and Subtraction. So
2*3-1is5, not4, and6+4/2is8, not5. - 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 bypi. To divide by \(2 \pi \), you can use parentheses or writedegrees / 2 / pi.
I don’t work very hard to remember the precedence of operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.
This page titled 2.5: Order of operations was last modified on Tue, 01 Dec 2020 03:30:50 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.