What operator is used to raise a number to a power in Python?
In Python the double asterisk operator
**
is used to help calculate the exponent of a number raised to a power. This is done without a need to import the Python math library.
For example, 2 to the power of 3 can be expressed using the double asterisk operator
2 ** 3
, here the resulting output with the Python REPL:
>>> 2 ** 3
8
The double asterisk operator is therefore the mathematical expression used in Python to calculate exponents. The first number being the base and the second number after the operator being the exponent or power.
Shortcut For Roots
The same double asterisk operator can also be used as a replacement for the math square root function too.
If you can remember math class you’ll recall that the square root symbol is just a number raised to the power of a half.
To express this using the double asterisk operator in the Python REPL looks as follows when finding the square root of 25:
>>> 25 ** (1/2)
5.0
The same came be applied to cube roots, quartic roots, etc.
>>> 27 ** (1/3)
3.0
>>> 16 ** (1/4)
2.0
The double asterisk operator can be used to perform calculations on any exponent, even fractions to help with calculating the values of roots.
Can The Double Asterisk Operator Be Used With Strings?
Besides operating on numbers can the double asterisk operator be used on other Python data types such as strings?
As the double asterisk takes two parameters to perform its calculation here are the results when the string is used as the base and the number as an exponent:
>>> "Base" ** 2
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
The TypeError is due to the unsupported type being used as the double asterisk operator cannot use strings in its operation. Interestingly the same error is thrown when using the
pow()
(
power
) function.
So strings cannot be used in the double asterisk operator, not like they can in the multiplication operator with strings.
Summary
The double asterisk operator provides a shortcut method of what the power function provides by calculating the exponent of a base number to its power.
The double asterisk operator cannot work on strings as is seen with other operations such as the multiplication operator when repeating a string multiple times.
Next, you might want to explore the single asterisk operator in Python which is used as a prefix on variable names .