TypeError: unsupported operand type(s) for +: 'decimal' and 'float'

TypeError: unsupported operand type(s) for +: 'decimal' and 'float'

我正在使用 Python 2.7 和 MySQLdb。我在这段代码上收到此错误:

Value = 5
x.execute("SELECT number from Testing where id ='%s';" % Value)
data = x.fetchall()
print (data)
data = data[0][0]
data = data + 0.5
x.execute(""" UPDATE Testing SET number = %s WHERE id = %s """, (data, Value))
conn.commit()

错误发生在行:data = data + 0.5.

TypeError: unsupported operand type(s) for +: 'decimal' and 'float'.

号码是DECIMAL(8,1)。我已经看到了这个错误的其他问题,但没有添加。另外,我认为有些人如果是 Python 的新手并且无法理解针对类似问题的更高级 Python 编码,他们也会遇到同样的问题。请你帮助我好吗?提前致谢。

这确实是一个例外加法:

from decimal import Decimal
Decimal('0.1') + 0.2

TypeError                                 Traceback (most recent call last)
<ipython-input-3-9bb7f0cfb622> in <module>()
      1 from decimal import Decimal
----> 2 Decimal('0.1') + 0.2

TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

您可能想这样做:

data = data + Decimal('0.5')

似乎不​​支持该操作,您必须先构建一个 Decimal 对象并添加:

In [132]:

import decimal
​
d = decimal.Decimal(23.0)
d = d + decimal.Decimal(0.5)
d
Out[132]:
Decimal('23.5')