python报错TypeError: unsupported operand type(s) for -: ‘decimal.Decimal‘ and ‘float‘

python报错TypeError: unsupported operand type(s) for -: ‘decimal.Decimal‘ and ‘float‘

img

朋友你好,观察了你的代码以及报错信息,该条报错出现在第48行,但是你的电脑屏幕显示不到48行,所以我只能基于当前报错为你提供解决思路。

TypeError: unsupported operand type(s) for -: ‘decimal.Decimal‘ and ‘float‘】这个错误是因为你正在尝试用一个float类型的值减去一个decimal.Decimal类型的值,而这两种类型不能直接进行减法运算。

要解决这个问题,你可以将float类型的值转换为decimal.Decimal类型,然后再进行减法运算。你可以使用decimal.Decimal的构造函数将float类型的值转换为decimal.Decimal类型。

希望得到你的采纳!

你那运行报错截图怎么变成两个str了,就是转成同一类型再减

  • 请看👉 :Python中运行报TypeError: unsupported operand type(s) for +: ‘float‘ and ‘str‘的解决方法
  • 除此之外, 这篇博客: python中TypeError: unsupported operand type(s) for ^: 'float' and 'int'的理解(简单)中的 ^ 在python的正确理解(初学者) 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 我在比较python中冒泡排序与选择排序的时间长短与及稳定性时,编了一段用于计算平均值,间距和方差的程序。
    代码如下:

    i=eval(input(":"))#给出数据个数
    list1=[]
    for x in range(0,i):
        list1.append(eval(input()))#输入数据
    list2=[]
    for n in range(0,i):
        list2.append((list1[n]-(sum(list1)/i))^2)
    print("最大与最小间距:",max(list1)-min(list1),"平均值:",sum(list1)/i,"方差为:",sum(list2)/i)
    

    程序随即出错:

    Traceback (most recent call last):
      File "C:/Users/22655/Desktop/yy.py", line 7, in <module>
        list2.append((list1[n]-(sum(list1)/i))^2)
    TypeError: unsupported operand type(s) for ^: 'float' and 'int'
    

    错在了list2.append((list1[n]-(sum(list1)/i))^2)一行中的 ^ 处,而错误指出float浮点数与int整数。
    放入数据为:

    5
    0.029918670654296875
    0.03444409370422363
    0.036663055419921875
    0.04584145545959473
    0.0288238525390625

    我便更改了代码:

    list2.append((list1[n]-(sum(list1)/i))**2)
    

    结果运行正确了

    最大与最小间距: 0.017017602920532227 平均值: 0.03513822555541992 方差为: 3.689622309593687e-05

    在IDLE的交互下探索(^)符号的意义:

    >>> (0.213253632)^2
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        (0.213253632)^2
    TypeError: unsupported operand type(s) for ^: 'float' and 'int'
    >>> (4)^2
    6
    >>> (4)*(4)
    16
    >>> (4)**2
    16
    >>> (0.213253632)**2
    0.04547711156119142
    >>> 
    

    原来我将 ^ 符号在python错误的理解为指数运算,在python中用指数运算一般采用 (**) 或者pow(a,b)

    
    >>> pow(2,5)
    32
    >>> pow(5,2)
    25
    >>> 2**5
    32
    >>> 5**2
    25
    

    而 ^ 在python中已经不是进行指数运算的意思了,

    ^是按位异或逻辑运算符

    明显 ^ 在python中是异或逻辑运算符
    什么是异或逻辑运算符呢?
    最为常见的有或逻辑运算符和与逻辑运算服,以下由例子来解释:
    或运算:

      01010101
    V 11001010
    ------------
      11011111
    

    或运算中0与1运算完后为1,1与1运算后为1,0与0运算后为0
    同理:
    与运算中0与1运算后为0,0与0运算后为0,1与1运算后为1
    ^代表的异或逻辑运算符的运算规则为:
    1与1运算后为0,1与0运算后为1,0与0运算为0
    以上的0,1均为二进制

    在python中运用^计算
    例如:

    >>> 5^2
    

    计算机会先把5和2分别转换为二进制
    5 ==> 101
    2 ==> 010
    再进行异或逻辑运算
    101^010 结果为111
    111 ==> 7 继而结果为7

    >>> 5^2
    7
    

    还有很多按位逻辑运算符我就不一一介绍了