为什么会出现 TypeError: can't multiply sequence by non-int of type 'float'?

新手上路,请多包涵

我正在输入以获取要乘以定义的销售税 (0.08) 的销售金额(通过输入),然后让它打印总金额(销售税乘以销售金额)。

我遇到了这个错误。任何人都知道什么可能是错的或有任何建议?

 salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax

Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'

原文由 SD. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 902
2 个回答

raw_input 返回一个字符串(一个字符序列)。在 Python 中,字符串和浮点数相乘没有明确的含义(而字符串和整数相乘有含义: "AB" * 3"ABABAB" ;多少是 "L" * 3.14 ? 请不要回复 "LLL|" )。您需要将字符串解析为数值。

您可能想尝试:

 salesAmount = float(raw_input("Insert sale amount here\n"))

原文由 Marc Gravell 发布,翻译遵循 CC BY-SA 2.5 许可协议

也许这会在将来帮助其他人——我在尝试将一个浮点数和一个浮点数列表相乘时遇到了同样的错误。问题是这里的每个人都在谈论将浮点数与字符串相乘(但这里我所有的元素一直都是浮点数)所以问题实际上是在列表上使用 \* 运算符。

例如:

 import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

错误:

     coff *= C
TypeError: can't multiply sequence by non-int of type 'float'

解决方案 - 将列表转换为 numpy 数组:

 coff = np.asarray(coff) * C

原文由 Serendipity 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题