【问题标题】:Python TypeError: unsupported operand type(s) for /: 'str' and 'float'Python TypeError:/:'str'和'float'不支持的操作数类型
【发布时间】:2013-10-29 02:11:54
【问题描述】:

我的代码:

total=tef+tpf-price

我遇到了这个错误:

  total=tef+tpf-price
unsupported operand type(s) for -: 'float' and 'str'

我该如何解决?

【问题讨论】:

  • 这个问题看起来与原来的问题完全不同。请改回来,然后开始一个新问题。

标签: python typeerror


【解决方案1】:

可能发生错误的唯一方法是price 是一个字符串。将价格设为浮点数或整数(取决于您想要什么)来解决问题。

要么:

tef=float(price)*5/100.0

或者这个:

tef=int(price)*5/100.0

请注意,在 Python 中,要在两个对象之间执行操作,这些对象必须是同一类型(当然也支持该操作)。

【讨论】:

  • 编辑了问题,我该如何解决?
  • @user2899653 - 您必须确保所有这些变量都属于同一类型。最有可能的是,这意味着让它们全部浮动。
  • 你能帮我做吗?
  • @user2899653 - 好吧,我不知道你的代码,所以我能做的最好的就是:total=float(tef)+float(tpf)-float(price)
【解决方案2】:

修复它的一个简单方法是:

tef=float(price)*5/100.0

【讨论】:

  • 编辑了问题,我该如何解决?
【解决方案3】:

我认为您可能会接受用户的price 输入,例如:

price = raw_input('--> ')    // Python 2.x

price = input('--> ')        // Python 3.x

所以你可能想在使用它之前做一些验证。

您可以将price 从字符串转换为由float(price) 浮动。

【讨论】:

  • 编辑了问题,我该如何解决?
  • 您需要将所有内容都转换为浮动
  • 你能帮我做吗?
【解决方案4】:

不是这个

total=tef+tpf-price

试试这个,希望对你有帮助

total=float(tef)+float(float)tpf-float(price)

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多