6. Precedence
When an expression mixes operators, Python evaluates them in a fixed order called precedence. Operators with higher precedence bind first.
From highest to lowest, the operators used in this chapter are:
**(power)- unary
+and-(for example-x) *,/,//,%+,-- comparisons (
<,<=,>,>=,==,!=) notandor
Operators on the same level are evaluated from left to right, except **, which groups from right to left.
Parentheses () override precedence: whatever is inside them is evaluated first.
Unary minus has lower precedence than **, so -2 ** 2 means -(2 ** 2):
not has lower precedence than comparisons, so not 2 > 3 means not (2 > 3).
and has higher precedence than or, so True or False and False means True or (False and False).
Multiplication before addition
Write 2 + 3 * 4 without parentheses, and print the result. Multiplication is evaluated before addition.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Parentheses first
Use parentheses to force 2 + 3 to be evaluated before multiplying by 4, and print the result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Power before multiplication
Write 2 * 3 ** 2 without parentheses, and print the result. The power operator (**) has higher precedence than multiplication.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Unary minus and power
Print -2 ** 2 without parentheses. The power operator (**) is evaluated before the unary minus, so the minus applies to the whole result of 2 ** 2.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
not and comparison
Print not 2 > 3 without parentheses. Comparisons are evaluated before not, so not applies to the result of 2 > 3.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
and before or
Print True or False and False without parentheses. The and operator is evaluated before or.
Print exactly:
Create a free account to save your progress and unlock chapter 2.