TypeError: unsupported operand type(s) for ^: float and int

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Devon MacKay

TypeError: unsupported operand type(s) for ^: float and int #

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.

typeerror unsupported operand type for caret float and int

Here is an example of how the error occurs.

main.py
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.

main.py
my_float = 3.3 my_int = 2 result = my_float ** my_int print(result) # 👉️ 10.889999999999999

Alternatively, you can use the math.pow() method.

main.py
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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.