python - 类型错误 : can't multiply sequence by non-int of type 'float'

标签 python

我是 Python 的菜鸟,一直没能解决这个问题。我希望能够将税收变量保留在代码中,以便在它发生变化时可以轻松更新。我尝试过不同的方法,但只能让它跳过打印税行并为总计和小计打印相同的值。如何将税收变量乘以总和(items_count)?这是代码:

   items_count = []
tax = float(.06)
y = 0

count = raw_input('How many items do you have? ')

while count > 0:
    price = float(raw_input('Please enter the price of your item: '))
    items_count.append(price)
    count = int(count) - 1

print 'The subtotal of your items is: ' '$%.2f' % sum(items_count)
print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
total = (sum(items_count) * tax) + sum(items_count)
print 'The total of your items is: ' '$%.2f' % total

最佳答案

如果您提供错误的回溯,将会有所帮助。我运行了你的代码,得到了这个回溯:

Traceback (most recent call last):
  File "t.py", line 13, in <module>
    print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
TypeError: can't multiply sequence by non-int of type 'float'

答案是这是一个优先级问题。如果您只是这样做:

sum(items_count) * tax

它会起作用,但是因为你有带有字符串和 % 的表达式接线员,调用 sum()被绑在绳子上,实际上你有:

<string_value> * tax

解决方案是添加括号以强制使用您想要的优先级:

print 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)

这是 Python 中运算符优先级的文档。

http://docs.python.org/reference/expressions.html#summary

请注意 %* 具有相同的优先级, 因此顺序由从左到右的规则控制。因此,字符串和对 sum() 的调用与 % 相连运算符,剩下的就是 <string_value> * tax .

请注意,除了括号,您还可以使用显式临时变量:

items_tax = sum(items_count) * tax
print 'The amount of sales tax is: ' '$%.2f' % items_tax

当您不确定发生了什么时,有时开始使用显式临时变量并检查每个临时变量是否设置为您期望的值有时是个好主意。

附言您实际上并不需要对 float() 的所有调用.值0.06已经是一个浮点值,所以只说:

tax = 0.06

我喜欢将初始零放在分数上,但您可以使用 tax = 0.06 中的任一个或 tax = .06 ,没关系。

我喜欢你如何通过包装 raw_input() 将价格转换为 float 价格来电float() .我建议你对 count 做同样的事情, 包装 raw_input()来电int()得到一个int值(value)。然后后面的表达式可以简单地是

count -= 1

count 有点棘手最初设置为一个字符串,然后重新绑定(bind)。如果愚蠢或疯狂的用户输入了无效计数,int()将引发异常;最好立即发生异常,就在调用 raw_input() 时发生,而不是后来在一个看似简单的表达式中。

当然你没有使用 y对于您的代码示例中的任何内容。

关于python - 类型错误 : can't multiply sequence by non-int of type 'float' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1976467/

相关文章:

Python从特定日期中提取周数

python - pyside/pyqt : when converting str() to QTreeWidgetItem() the str() is shortened to the [0] of str()

python - 我需要帮助在不使用 bin 的情况下将代码中的二进制转换为十进制

python - 如何从编译的 .exe 文件将帮助打印到终端窗口?

python - 显示在模板中存储为二进制 blob 的图像

python - 如何在 Python 列表中的特定元素之后删除列表中的元素(切片不适用)

python - 是否可以使用python的类型函数动态创建类级别变量?

python - 过滤一个 Excel 工作表中的数据框并导出到另一个 Excel 工作表

python - ast.literal_eval - 遍历列表中的字符串元素

python - 如何在python中检查datetime模块的版本?