此代码需要允许输入最多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)发布于 2015-06-22 11:39:57
让我们来关注一下你的代码在做什么。
choice01 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")当用户回答这个问题时,他们的答案是一个字符串。它现在在choice01中。对于这个例子,让我们假设他们输入"pie“(没有引号)。
我们对choice02 =行重复此操作,用户选择"coffee“。
让我们看一下只有这两个选项的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个可能的值和相关的价格。"nothing“的值为0.00,因为您在成本计算中使用了该值。它使数学变得简单,而且它是有效的,因为你假设总是会有3个选择。
重要的是要注意,使用这种方法,如果用户键入他们的答案(即,"cofee“而不是”cofee“),它将抛出一个异常。这是一项由您决定如何处理此类错误的活动。有很多点你可以添加这样的检查。
其他修复
您还需要解决其他一些问题:
按照您的代码原样,
while choice:将无法正常工作。你没有定义choice。另一种方法是简单地执行while True,然后在循环结束时中断。示例:
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“键,因为您在将选择添加到成本之前打破了循环。
发布于 2015-06-22 11:30:12
您在顶部定义的是派、咖啡和冰淇淋的变量名。
您从raw_input获得的是文本字符串。
它们不会仅仅因为相同而匹配,你必须以某种方式匹配它们。我建议更多的是:
pie = 2.75
coffee = 1.50
icecream = 2.00
cost = 0
while True:
choice = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")
if choice == "nothing":
break
if choice == "pie":
cost = cost + pie
if choice = "coffee":
cost = cost + coffee
#... etc.
print "Your total is: ${0}".format(cost)如果你想避免大量的if语句,看看@Evert建议的一个保存价格的字典。
发布于 2015-06-22 11:33:40
看起来你根本不需要三个选择。考虑以下代码
pie = 2.75
coffee = 1.50
icecream = 2.00
cost = 0
while True:
choice01 = 0
choice01 = raw_input("What would you like to buy? pie, coffee, icecream, or nothing?")
if choice01 == "nothing":
break
elif choice01=="coffee":
choice01 = coffee
elif choice01=="pie":
choice01 = pie
elif choice01=="icecream":
choice01==icecream
else:
choice01=0
cost+=choice01
print "Your total is: ${0}" .format(cost)https://stackoverflow.com/questions/30971683
复制相似问题