gpt4 book ai didi

python - 我在我的代码 python 中做错了什么,它不会打印总成本?

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:15 25 4
gpt4 key购买 nike

此代码需要允许最多 3 个所需元素的输入,并打印所有元素的总成本。我对这一切都很陌生,需要我能得到的所有建议。我无法打印出总数。

pie = 2.75
coffee = 1.50
icecream = 2.00

while choice:

choice01 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")

if choice01 == "nothing":
break

choice02 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")

if choice02 == "nothing":
break

choice03 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")

if choice03 == "nothing":
break

cost = choice01+choice02+choice03


print "Your total is: ${0}" .format(cost)

最佳答案

让我们关注您的代码在做什么。

choice01 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")

当用户回答这个问题时,他们的答案是一个字符串。它现在位于 choice01 中。对于此示例,我们假设他们键入“pie”(无引号)。

我们用 choice02 = 行重复这个,用户选择“咖啡”。

让我们看看只有这两个选项的 cost = 行。

cost = choice01 + choice02

我们刚刚确定 choice01 是字符串值“pie”,choice02 是字符串值“coffee” 因此,cost = "piecoffee"


你如何解决这个问题?

您想在顶部使用这些变量。一种方法是创建字典:

prices = {"pie": 2.75,
"coffee": 1.50,
"icecream": 2.00,
"nothing": 0.00
}

...

cost = prices[choice01]+prices[choice02]+prices[choice03]

我做了什么?

在字典中,我设置了你的 4 个可能的值和相关的价格。 “无”的值为 0.00,因为您在成本计算中使用了它。它使数学变得简单并且有效,因为您假设总会有 3 个选择。

请务必注意,使用此方法时,如果用户打错了答案(即“cofee”而不是“coffee”),它将引发异常。这是一项让您确定要如何处理此类错误的事件。您可以在多个方面添加此类检查。


其他修复

您还需要修复一些其他问题:

  • while choice: 不会像您的代码那样工作。您没有定义 choice。另一种方法是简单地执行 while True ,然后在循环结束时跳出。
  • 您可以将整个输入循环压缩为仅一个简单的询问并添加到运行总计中。这将使您有 3 个以上的选择。

例子:

prices = {"pie": 2.75,
"coffee": 1.50,
"icecream": 2.00
}

cost = 0.00
while True:
choice = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")
if choice == "nothing":
break
cost = cost + prices[choice]

print "Your total is: ${0}" .format(cost)

输出:

What would you like to buy? pie, coffee, icecream, or nothing? pie
What would you like to buy? pie, coffee, icecream, or nothing? nothing
Your total is: $2.75

请注意,我们只有一次用户输入问题,并且我们在循环开始之前定义了 cost。然后我们每次通过循环添加到它。我还从字典中删除了“nothing”键,因为您在将选择添加到成本之前就跳出了循环。

关于python - 我在我的代码 python 中做错了什么,它不会打印总成本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com