我试图在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美元我的结果应该是数量* productPrice:
"Here's your bag with 1 Tomatos. The total is $0.00."
为什么失败?我在这里缺少什么?
我正在使用Python 3.x
提前致谢!
答案 0 :(得分:2)
您正在迭代输入中的字符,并设置每次支付的价格。没有必要进行迭代,因为product
不会改变。删除for
循环就可以了。您还需要删除对productChoice
的引用,因为它(字面上)没有任何意义。
#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? "))
if product == "Potato":
pricePaid = quantity * potato
elif product == "Tomato":
pricePaid = quantity * tomato
elif product == "Carrot":
pricePaid = quantity * carrot
print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
答案 1 :(得分:2)
这导致了您的问题:
for productChoice in product:
if productChoice == "Potato":
pricePaid = quantity * potato
elif productChoice == "Tomato":
pricePaid = quantity * tomato
elif productChoice == "Carrot":
pricePaid = quantity * carrot
如果我们快速改变这一点,我们可以看到原因
for productChoice in product:
print(productChoice)
产品为“番茄”的输出
T
o
m
a
t
o
当你实际上不想要这种行为时,你在这里做的是迭代字符串product
中的每个字符。解决问题的方法就是删除for循环,仅保留选择。
这就是你所需要的:
if product == "Potato":
pricePaid = quantity * potato
elif product == "Tomato":
pricePaid = quantity * tomato
elif product == "Carrot":
pricePaid = quantity * carrot
希望这有帮助!
答案 2 :(得分:1)
您正在迭代producChoice
中的字母。
在循环中添加print(productChoice)
以观察发生的情况。
由于没有一个字母等于您的某个产品,因此不会触发任何条件语句,并且pricePaid
将保持其原始值int() == 0
。
根本不需要for
循环,所以只需删除它。
答案 3 :(得分:1)
这是使用词典的改进代码。单单词典值得研究,以使代码更轻松。基本上,字典由持有值(例如1)的键(例如番茄)组成。您可以使用.get()。
获取这些值#products list and it's values per unity
prices = dict(tomato=2,potato=3,carrot=1)
product = input('''\
Welcome to my grocery shop!
What will you want today?
We have: {}
What will it be?
'''.format(', '.join(prices.keys()))).lower()
quantity = int(input("And how many do you want? "))
pricePaid = prices.get(product,0) * quantity
if pricePaid:
print("Here's your bag with {0} {1}s. The total is ${2:.2f}."
.format(quantity, product, pricePaid))
else:
print("Error with input!")