Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Devon MacKay
The Python "TypeError: unsupported operand type(s) for ^: float and int" occurs when we use the bitwise XOR operator when we meant to use the exponentiation operator. To solve the error, use the exponentiation (**) operator instead.
Here is an example of how the error occurs.
my_float = 3.3 my_int = 2 # ⛔️ TypeError: unsupported operand type(s) for ^: 'float' and 'int' result = my_float ^ my_int
The caret ^
symbol is the bitwise XOR (exclusive or) operator.
To solve the error use the exponentiation (**) operator instead.
my_float = 3.3 my_int = 2 result = my_float ** my_int print(result) # 👉️ 10.889999999999999
Alternatively, you can use the math.pow()
method.
import math my_float = 3.3 my_int = 2 result = math.pow(my_float, my_int) print(result) # 👉️ 10.889999999999999
The math.pow method
takes 2 numbers - x
and y
and returns x
raised to the power of y
.
Unlike the built-in **
(exponentiation) operator, math.pow()
converts both
of its arguments to type float
.
If you need to compute exact integer powers, use the **
operator or the
built-in pow()
function.
import math my_int = 2 my_other_int = 4 print(pow(my_int, my_other_int)) # 👉️ 16 print(my_int ** my_other_int) # 👉️ 16 print(math.pow(my_int, my_other_int)) # 👉️ 16.0
Notice that the math.pow()
method returns a float value because it converts
both of its arguments to floats.