我的python乘法不起作用

2024-10-02 00:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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

提前谢谢!你知道吗


Tags: foritproductquantitypotatointprinttomato
3条回答

您正在迭代producChoice中的字母。你知道吗

向循环中添加print(productChoice),以便观察发生了什么。 因为没有一个字母等于一个产品,所以不会触发任何条件语句,pricePaid将保持其原始值int() == 0。你知道吗

这里根本不需要for循环,所以只需删除它。你知道吗

您正在迭代输入中的字符,并设置每次支付的价格。不需要迭代,因为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))

这导致了您的问题:

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

希望这有帮助!你知道吗

相关问题 更多 >

    热门问题