我试图在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."
为什么会失败?我错过了什么?你知道吗
我正在使用python3.x
提前谢谢!你知道吗
您正在迭代
producChoice
中的字母。你知道吗向循环中添加
print(productChoice)
,以便观察发生了什么。 因为没有一个字母等于一个产品,所以不会触发任何条件语句,pricePaid
将保持其原始值int() == 0
。你知道吗这里根本不需要
for
循环,所以只需删除它。你知道吗您正在迭代输入中的字符,并设置每次支付的价格。不需要迭代,因为
product
不变。去掉for
循环就可以了。您还需要删除对productChoice
的引用,因为它(字面上)没有任何用途。你知道吗这导致了您的问题:
如果我们很快把它改成这样,我们就能明白为什么了
产品为“番茄”的产量
您在这里所做的是迭代字符串
product
中的每个字符,而实际上您并不需要这种行为。解决问题的方法就是去掉for循环,只保留选择。你知道吗这就是你所需要的:
希望这有帮助!你知道吗
相关问题 更多 >
编程相关推荐