gpt4 book ai didi

python - 尝试获取两个附加值的字符串并将它们相减

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:43 25 4
gpt4 key购买 nike

如图所示,我已编写此代码并为 CASH 和 TOTAL 分配了值。我不明白的是为什么我得到......“回溯(最近一次调用最后一次): 文件“C:\Python27\Checkout Counter2.py”,第 29 行,位于 找零=现金-总额类型错误:不支持的操作数类型 -:“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)

最佳答案

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

因此你必须:

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

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

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

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

希望有帮助。

关于python - 尝试获取两个附加值的字符串并将它们相减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com