In math, we use order of operations. Multiplication and division goes first, unless brackets, then addition and subtraction. Python also has them, just with more rules.
The order of operations goes from highest to lowest rank, in order:
- parentheses ( 1+1 ) * 2
- exponents 1 ** 2
- unary plus and minus +a, -a
- multiplication, division, remainders ( 1 * 2 / 1 ) % 3
- addition and subtraction 1 + 1 – 2
- comparing operators 1 < 2, 2 > 1, 3 == 3, 1 != 2, 1 <= 2 , 2 >= 1
- boolean NOT (not) x = True; not x False
- boolean AND (and) x = True; y = True; x and y = True
- boolean OR (or) x = True; y = False; x or y = True
In Python order of operations, these go in order.
Here are some examples:
n = (6 + 7 * 2)
print(n)
First, multiply 7 by 2. The answer is 14. Then add 14 to 6, making 20. If your answer was 26, then you have not considered order of operations. In the list above, multiplication goes before addition. Try running this code to see if Python will answer with 20 or 26.
a = (2 ** 3 / 4)
print(a)
Exponents go before division. 2 to the power of 3 (2 x 2 x 2) is 8. 8 / 4 is 2.
m = (8 * 3 + (19 - 5))
print(m)
Should we multiply 8 by 3 first? After all, multiplication is before subtraction, right? But there are parentheses in the subtraction. Parentheses go before multiplication, so we have to do the subtraction first. 19 – 5 is 14. Now the parentheses have been removed (we solved 19 – 5), we can do 8 * 3, which is 24. Then, 24 + 14 equals to 38.
h = (8 >= 8 or 9 == 10)
print(h)
In the first statement, 8 is bigger or equal to 8. So that’s True. But 9 is not 10, so now it’s True or False, which outputs False.