I have "TypeError: unsupported operand type(s) for /: " for this code
class Foo(object):
def __add__(self, other):
return print("add")
def __div__(self, other):
return print("div")
Foo() + Foo()
add
** BUT for / **
Foo() / Foo()
Traceback (most recent call last):
File "<ipython-input-104-8efbe0dde481>", line 1, in <module>
Foo() / Foo()
TypeError: unsupported operand type(s) for /: 'Foo' and 'Foo'
The Python "TypeError: unsupported operand type(s) for /: 'str' and 'str'" occurs when we try to use the division / operator with two strings. To solve the error, convert the strings to int or float values, e.g. int(my_str_1) / int(my_str_2) . Here is an example of how the error occurs. main.py. Copied!
Unsupported operand type(s) for +: 'NoneType' and 'int' # The Python "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'" occurs when we try to use the addition (+) operator with a None value. To solve the error, figure out where the variable got assigned a None value and correct the assignment.
There are a number of “unsupported operand type(s)” errors in Python. These errors mean the same thing: you are trying to perform a mathematical operation on a string and a numerical value. Because strings do not support mathematical operations, you'll encounter an error.
The Python "TypeError: unsupported operand type(s) for +: 'int' and 'list'" occurs when we try to use the addition (+) operator with a number and a list. To solve the error, figure out where the variable got assigned a list and correct the assignment, or access a specific value in the list.
Python3 uses special division names: __truediv__
and __floordiv__
for the /
and //
operators, respectively.
In Python3, the /
is a true division in that 5/2
will return the floating point number 2.5
. Similarly 5//2
is a floor division or integer division because it will always return an int, in this case 2
.
In Python2 the /
operator worked the same way that the //
operator works in Python3. Because of the way that the operators changed between versions, the __div__
name was removed to to avoid ambiguity.
Reference: http://www.diveintopython3.net/special-method-names.html#acts-like-number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With