When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. Python follows the same precedence rules for its mathematical operators that mathematics does.
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 though it doesn’t change the result.2**1+1
is 3 and not 4, and 3*1**3
is 3 and not 27. Can you explain why?2*3-1
yields 5 rather than 4, and5-2*2
is 1, not 6.6-3+2
, the subtraction happens first, yielding 3. We then add 2 to get the result 5. If the operations had been evaluated from right to left, the result would have been 6-(3+2)
, which is 1.Note
Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation operator **. A useful hint is to always use parentheses to force exactly the order you want when exponentiation is involved: