Python Exponentiation and Operator Precedence
Powers and grouping
Use base ** exponent for exponentiation. With a nonnegative integer exponent, a whole-number base produces an integer. For example, 3 ** 2 multiplies three by itself twice. Parentheses explicitly group an expression.
The outputs are 9, 8 and 0.25. For a nonzero integer base, a negative integer exponent gives a float reciprocal.
Which operation groups first?
print(2 + 3 * 4 ** 2)print((2 + 3) * 4 ** 2)print(2 ** 3 ** 2)In these arithmetic expressions, powers bind more tightly than multiplication, division and remainder; those bind more tightly than addition and subtraction. Operators of the same multiplicative or additive level group left to right. Powers group right to left, so the final expression is 2 ** (3 ** 2), not (2 ** 3) ** 2.
Unary minus and parentheses
Unary minus negates one value. A power binds more tightly than a unary minus on its left, so -3 ** 2 means -(3 ** 2). On its right, a signed exponent is allowed, as in 2 ** -2. The operator ^ is not exponentiation; its bitwise meaning is taught later.
Practice
A square garden has side length six. Calculate its area, then subtract four units for a path. Write a second expression that squares the difference between six and four. Explain why the two results differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Power and expression grouping
Check your understanding of exponentiation and precedence.
What is printed?
print(3 ** 4)What is printed?
print((2 + 3) ** 2)What is printed?
print(-4 ** 2)How does 2 ** 2 ** 3 group?
Which expression represents a square of side n plus a fixed area of 5?