提问人:Battlecode222 提问时间:11/17/2023 更新时间:11/17/2023 访问量:43
如何使用Python字典和多个字典进行计算?
How to perform calculation with Python dictionary and multiple?
问:
我这里有这段代码,它会产生一个逻辑错误。该程序的目标是让用户从字典列表中输入食物,然后输入用户想要的食物数量。然后程序将计算用户选择的食物总数的总成本。这段代码允许用户这样做,但在计算超过 10 和超过 20 的食品时,计算是不正确的。任何数量超过 10 和超过 20 的食品尽管在计算范围内,但不会计算倍数total_cost。例如,如果用户选择了 12 根香蕉,那么价格应该是 21.09 美元,而我的代码输出的是 22.20 美元,因为它由于某种原因没有在计算中注册倍数。我想知道是什么原因导致此问题发生,我将如何解决?需要明确的是,10-20 岁的食品有 5% 的折扣,而 20 岁以上的食品有 10% 的折扣。低于 10 的食品在此计划中没有折扣。
purchase = {"bananas": 1.85, "steak": 19.99, "cookies": 4.52, "celery": 2.81, "milk": 4.34}
#cost per item: <10 is full price, 10-20 (inclusive) is 5% discount, and 21+ is 10% discount
#solution accepts a string input representing an item (dictionary key)
#solution accepts an integer input representing the number of items to be purchased
#solution outputs the item and total cost of purchase
food_item = input()
number_of_items = int(input())
if food_item in purchase:
if purchase[food_item] < 10:
total_cost = number_of_items * purchase[food_item]
elif 10 <= purchase[food_item] <= 20:
total_cost = number_of_items * purchase[food_item] * .95
else:
total_cost = number_of_items * purchase[food_item] * .90
print(f"{food_item} ${total_cost:.2f}")
答: 暂无答案
评论