Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by earthswell
The Python "TypeError: unsupported operand type(s) for *: 'float' and
'builtin_function_or_method'" occurs when we forget to call a builtin function
or method. To solve the error, make sure to call the function, e.g.
math.sqrt(25)
.
Here is an example of how the error occurs.
import math my_number = 10.5 # ⛔️ TypeError: unsupported operand type(s) for *: 'float' and 'builtin_function_or_method' result = my_number * math.sqrt
We forgot to invoke the math.sqrt
method so we ended up trying to multiply a
number and a method.
To solve the error, make sure to call the method.
import math my_number = 10.5 result = my_number * math.sqrt(25) print(result) # 👉️ 52.5
We used parenthesis to call the method, so we can get its return value.
my_func(10, 20)
.If you aren't sure what type a variable stores, use the built-in type()
class.
import math my_number = 10.5 print(type(my_number)) # 👉️ <class 'float'> print(isinstance(my_number, float)) # 👉️ True print(type(math.sqrt)) # 👉️ <class 'builtin_function_or_method'> print(callable(math.sqrt)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.
The callable
function takes an object as an argument and returns True
if the object appears
callable, otherwise False
is returned.
If the callable()
function returns True
, it is still possible that calling
the object fails, however if it returns False
, calling the object will never
succeed.