【问题标题】:TypeError: unsupported operand type(s) for -=: 'str' and 'float'类型错误:-= 不支持的操作数类型:\'str\' 和 \'float\'
【发布时间】:2022-12-03 18:24:30
【问题描述】:

我试图编写一个将十进制转换为二进制的程序,反之亦然,但是当我尝试 23 时,它会将第 17 行 (answer2 -= x) 标记为类型错误。

    import math

    x = 4096
    y = ""
    z = 10
    q = 1
    final_answer = 0

    answer1 = str(input("Do you want to convert decimal into binary (1) or binary into decimal      (2)?"))
    if answer1 == "1":
        answer2 = input("What number do you want to convert to binary? It can't be larger than   4096")
        p = answer2.isdigit()
        if p:
            for i in range(13):
                if int(answer2) >= x:
                    y = y + "1"
                    answer2 -= x
                else:
                    y = y + "0"

                x /= 2

            print(y)
        elif not p:
            print("That's not a number")

我试图将 answer2 和 x 的变量转换为 float 和 int 但同样的问题仍然出现。

【问题讨论】:

  • 您可以永久转换“answer2”:answer2 = int(answer2)

标签: python


【解决方案1】:

当您应用涉及数值的操作时,您的变量仍然是一个字符串。在您的情况下,您仍然需要将变量转换为浮点数:

answer2 = float(answer2)

此外,我不知道 isdigit() 是否捕获浮点数(涉及小数点)。如果你被困在那里,这篇文章可能会有所帮助:Using isdigit for floats?

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 2013-05-08
    • 1970-01-01
    • 2017-05-27
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多