我是Python的菜鸟,并没有任何运气搞清楚这一点.我希望能够将税变量保留在代码中,以便在更改时可以轻松更新.我已经尝试了不同的方法,但只能跳过打印税行并打印相同的总数和小计值.如何将税变量乘以sum(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
Run Code Online (Sandbox Code Playgroud)
如果您为错误提供反向跟踪,这将有所帮助.我运行了你的代码,得到了这个回溯:
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'
Run Code Online (Sandbox Code Playgroud)
答案是这是一个优先问题.如果你这样做:
sum(items_count) * tax
Run Code Online (Sandbox Code Playgroud)
它会工作,但因为你有字符串和%运算符的表达式,调用将sum()绑定到字符串,实际上你有:
<string_value> * tax
Run Code Online (Sandbox Code Playgroud)
解决方案是添加括号以强制您想要的优先级:
print 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
当您不确定发生了什么时,有时最好开始使用显式临时变量,并检查每个变量是否设置为您期望的值.
PS你实际上并不需要所有的电话float().该值0.06已经是浮点值,因此只需说:
tax = 0.06
Run Code Online (Sandbox Code Playgroud)
我喜欢将初始零点放在分数上,但你可以使用tax = 0.06或者tax = .06,它没关系.
我喜欢你如何转换价格通过包装漂浮raw_input()呼叫float().我建议您应该做同样的事情count,包装raw_input()调用int()以获取int值.然后后面的表达式就可以了
count -= 1
Run Code Online (Sandbox Code Playgroud)
这有点棘手,count最初设置为字符串,然后重新绑定.如果愚蠢或疯狂的用户输入无效计数,int()则会引发异常; 最好是异常发生,就在调用时raw_input(),而不是后来看似简单的表达式.
当然,您不会y在代码示例中使用任何内容.