Sub topic 2
Grouping symbols come first
This chapter assumes you can add, subtract, multiply, and divide integers, and that you read a fraction as a numerator over a denominator. Negative integers and fraction arithmetic are used throughout.
An order of operations gives an expression one value. Without an agreed order, 2 + 3 * 4 could mean 20 or 14.
Grouping symbols come first
Evaluate anything inside parentheses ( ) or brackets [ ] before you work on the terms outside them.
Putting the levels together
Apply the levels in this order:
- Grouping symbols
- Exponents
- Multiplication and division, left to right
- Addition and subtraction, left to right
Operations at the same level run left to right. So 24 / 4 * 3 equals 18.0, not 2.0.
Nested parentheses and brackets
Work from the innermost group outward.
print(2 * (3 + (4 - 1))) # 12: 4 - 1 = 3, then 3 + 3 = 6, then 2 * 6 = 12Negative numbers and exponents: -3^2 versus (-3)^2
An exponent applies before a minus sign unless parentheses make the negative number the base.
print(-3 ** 2) # -9: 3 ** 2 = 9, then negate
print((-3) ** 2) # 9: the base is -3Order of operations with fractions
A fraction bar groups everything above it and everything below it. Evaluate the top and the bottom separately, then divide.
from fractions import Fraction
print((3 + 5) / (2 + 2)) # 2.0
print(3 + 5 / 2 + 2) # 7.5: only the 5 is divided by 2
result = Fraction(1, 2) + Fraction(3, 4) * Fraction(2, 3) ** 2
print(result) # 5/6For the last line, (2/3)^2 = 4/9, then 3/4 * 4/9 = 1/3, then 1/2 + 1/3 = 5/6.
Exercise
Evaluate 2 + 3 (4 - 1) * 2.
Show answer
29. Inside the parentheses, 4 - 1 = 3. Then 3 * 2 = 9, and 3 9 = 27. Finally, 2 + 27 = 29.