【问题标题】:Trying to take two strings with values attached and subtract them试图取两个带有附加值的字符串并减去它们
【发布时间】:2015-03-01 06:14:57
【问题描述】:

如图所示,我编写了这段代码并为 CASH 和 TOTAL 分配了值。我无法理解的是为什么我得到...... “回溯(最近一次通话最后一次): 文件“C:\Python27\Checkout Counter2.py”,第 29 行,在 零钱=现金-总计 TypeError: 不支持的操作数类型 -: 'str' 和 '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) 

【问题讨论】:

    标签: python string


    【解决方案1】:

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

    因此你必须:

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

    编辑:另外,当你这样做时:

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

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

    希望对你有帮助。

    【讨论】:

    • 好的,谢谢。这解决了我的问题。我忘记了 raw_input。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多