计算批量订单的价格-请求公式/计算帮助

  • 本文关键字:计算 请求 帮助 python
  • 更新时间 :
  • 英文 :


我是python的新手,在我制定的练习程序中有点吃力。

目标

如果数量小于等于100,则每个成本为350美元。

如果数量在200或以下,前100个单位的价格为350美元,任何东西不到200,但超过100的成本是300美元。

如果数量为200或更多,前100个单位的价格为350美元,下一个单位100的成本为300美元,超过200的成本为250美元。

计算总订单的价格。


quantities = [84, 100, 126, 150, 186, 200, 216, 248]
cost = 0
for i in range(len(quantities)):
if quantities[i] <= 100:
cost = (quantities[i] * 350)
print(f"The cost for an order of {quantities[i]} is ${cost}.")
elif quantities[i] >= 100 and quantities[i] <= 200:
cost = cost + (quantities[i] * 300)
print(f"The cost for an order of {quantities[i]} is ${cost}.")
elif quantities[i] >= 200:
cost = cost + (quantities[i] * 250)
print(f"The cost for an order of {quantities[i]} is ${cost}.")

我得到的答案:

The cost for an order of 84 is $29400. 
The cost for an order of 100 is $35000. 
The cost for an order of 126 is $72800. 
The cost for an order of 150 is $117800. 
The cost for an order of 186 is $173600. 
The cost for an order of 200 is $233600. 
The cost for an order of 216 is $287600. 
The cost for an order of 248 is $349600.

我应该得到的答案:

The cost for an order of 84 is $29400. 
The cost for an order of 100 is $35000. 
The cost for an order of 126 is $42800. 
The cost for an order of 150 is $50000. 
The cost for an order of 186 is $60800. 
The cost for an order of 200 is $65000. 
The cost for an order of 216 is $69000. 
The cost for an order of 248 is $77000.
Where am I going wrong in my calculation?

这里有两个主要问题。

  1. 您在块中使用cost = cost + ...语句,但您使用的是elif。这意味着这三个块中只有一个将在循环的每次迭代中执行。在循环的每次迭代中,也不会将cost重置为0

  2. 您将成本应用于订单的全部数量,并且缺少您在要求中要求的仅将其应用于特定范围的逻辑

如果我正确理解你的要求,计算成本应该看起来像下面的

def calc_cost(quantity):
if quantity <= 100:
return 350 * quantity
elif quantity > 100 and quantity <= 200:
return 100 * 350 + (quantity - 100) * 300
else:
return 100 * 350 + 100 * 300 + (quantity - 200) * 250

然后你可以用下面的显示你的计算

In [5]: for quantity in quantities:
...:     print(f'The cost of an order of {quantity} is {calc_cost(quantity)}')
...:
The cost of an order of 84 is 29400
The cost of an order of 100 is 35000
The cost of an order of 126 is 42800
The cost of an order of 150 is 50000
The cost of an order of 186 is 60800
The cost of an order of 200 is 65000
The cost of an order of 216 is 69000
The cost of an order of 248 is 77000

(额外语法帮助(在python中,您不必使用索引进行迭代,您可以轻松地执行上面所示的for quantity in quantities

最新更新