我的Python乘法运算不起作用。

3

我正在尝试在下面的代码中使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。

提前致谢!


1
我认为 for productChoice in product: 并不是你想象中的那样。因为 product 是一个字符串(input 返回字符串),所以 productChoice 将会是你输入的每个字母。 - R Nar
4个回答

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))

谢谢,@jhpratt。这很有帮助。 - RGregg

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)

使用“Tomato”作为产品的输出结果
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

希望这能帮到您!

1
你正在迭代 productChoice 中的字母

在循环中添加 print(productChoice) 以观察发生了什么。 由于没有单个字母等于你的产品之一,因此不会触发任何条件语句,pricePaid 将保持其原始值,即 int() == 0

这里根本不需要使用 for 循环,所以只需将其删除即可。


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!")


1
尽管这可能有效,但它完全改变了手头的代码,并且没有为帖子发布者提供任何关于为什么他们的代码失败的帮助。 - jhpratt
1
但是谁能说他们甚至理解你的重写后代码的作用呢? - jhpratt
谢谢,@AntonvBR。看到如何重写我的代码很有帮助。我确实理解,但需要一段时间来吸收这个概念。非常感谢你的回答! - RGregg
@RGregg 我明白了,看起来你已经熟悉解包和字符串格式化。字典很容易学习!试试吧! - Anton vBR
@RGregg 这段代码与 if 语句的一个区别是,如果您输入不支持的产品,这段代码将失败。这可能是一个特性或一个缺陷,取决于您的观点。 - Mark Ransom
@RGregg,是的,目前还没有处理输入错误的功能。 - Anton vBR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接