尝试获取两个附加值的字符串并将其减去



如图所示,我已经编写了这段代码,并为CASH和TOTAL分配了值。我不明白的是我为什么会。。。。。"Traceback(最近一次通话):文件"C:\Python27\Checkout Counter2.py",第29行,位于零钱=现金总额TypeError:不支持-:"str"one_answers"str’"的操作数类型

我已经尝试了多种方法来实现这一点,我看不出这与它找到总数有什么区别。

 print "Welcome to the checkout counter!  How many items are you purchasing today?"
    #NOI is number of items
    NOI = int(raw_input())
    productlist = []
    pricelist=[]
    for counter in range(NOI):
        print"Please enter the name of product", counter+1 
        productlist.append(raw_input())    
    print"And how much does", productlist[len(productlist)-1], "cost?"
    pricelist.append(float(raw_input()))
    if pricelist[len(pricelist)-1] < 0:
        pricelist.pop()
        productlist.pop()
        len(productlist)-1
        len(pricelist)-1
print "Your order was:"
subtotal=0.00
for counter in range(NOI):
    print productlist[counter],
    print "$%0.2f" % pricelist[counter]
    subtotal += pricelist[counter]
    total = "$%0.2f" % float(subtotal + (subtotal * .09))
print "Your subtotal comes to", "$" + str(subtotal) + ".", " With 9% sales tax, your total is " + str(total) + "."
print "Please enter cash amount:"
cash = raw_input()
while True:
    change = cash - total
    if cash < total:
        print "You need to give more money to buy these items. Please try again."
    else:
        print "I owe you back", "$" + float(change) 

"raw_input"将始终返回字符串(即使输入3或3.5)

因此,您必须:

cash = float(cash)
total = float(total)

编辑:当你这样做时:

total = "$%0.2f" % float(subtotal + (subtotal * .09))

total也将是一个字符串,这就是为什么您还必须将其转换为float。

希望能有所帮助。

最新更新