我正在尝试在下面的代码中使for循环内的乘法运算正常工作:
#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()
print("Welcome to my grocery shop!\n")
productList = ["Potato", "Tomato", "Carrot"]
print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")
quantity = int(input("And how many do you want? "))
for productChoice in product:
if productChoice == "Potato":
pricePaid = quantity * potato
elif productChoice == "Tomato":
pricePaid = quantity * tomato
elif productChoice == "Carrot":
pricePaid = quantity * carrot
print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
但是我的结果显示为$0.00,而实际上应该是数量乘以产品价格:
"Here's your bag with 1 Tomatos. The total is $0.00."
为什么它会失败?我在这里漏掉了什么吗?
我正在使用Python 3.x。
提前致谢!
for productChoice in product:
并不是你想象中的那样。因为product
是一个字符串(input
返回字符串),所以productChoice
将会是你输入的每个字母。 - R Nar