类型错误:无法用非整型的浮点数乘以序列

1 投票
4 回答
8110 浏览
提问于 2025-04-15 17:27

我刚接触Python,对这个问题还不太懂。我想在代码里保留一个税率变量,这样如果税率有变化就能方便地更新。我尝试了不同的方法,但只成功让程序跳过打印税率的那一行,最后打印出的总金额和小计都是一样的。我该怎么把税率变量和物品数量的总和相乘呢?下面是我的代码:

   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

4 个回答

1

你需要使用

'$%.2f' % (sum(items_count) * tax)

而不是

'$%.2f' % sum(items_count) * tax

你用的那个会被计算成 ('$%.2f' % sum(items_count)) * tax,这会出错(因为你把一个字符串和一个浮点数相乘了)。

1

你需要在 sum(items_count) * tax 周围加上括号。

我顺便把你的代码稍微整理了一下 :)

items_count = []
tax = float(.06)

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

while count:
    price = float(raw_input('Please enter the price of your item: '))
    items_count.append(price)
    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)
print 'The total of your items is: $%.2f' % ((sum(items_count) * tax) +
        sum(items_count))
5

如果你能提供错误的回溯信息,那会很有帮助。我运行了你的代码,得到了这个回溯信息:

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.06tax = .06,这没关系。

我喜欢你通过将 raw_input() 调用包裹在 float() 中来转换价格为浮点数。我建议你对 count 也这样做,把 raw_input() 调用包裹在 int() 中,以获得一个 int 值。这样后面的表达式就可以简单地是:

count -= 1

有点棘手的是,count 最初被设置为字符串,后来又重新绑定。如果一个傻乎乎或疯狂的用户输入了无效的计数,int() 会抛出异常;最好是在调用 raw_input() 时就让异常发生,而不是在后面的简单表达式中。

当然,你在代码示例中并没有使用 y

撰写回答