我创建了此功能,它通过字典进行迭代。我有一个价格命令,存储了一个项目的每个价格。然后是客户订单字典,存储每个客户的每个订单。
对于客户订单中的每个项目,我都将其乘以价格, 例如...
order 1: 10 books * $10.0
在此功能结束时,如果总订单金额超过$ 100,我将给予10%的折扣。高于$ 50则为5%,低于$ 50则没有折扣。
现在,由于某些原因,我无法在下面更改断言语法。.必须坚持其中的格式和代码,问题是我遇到断言错误。最终应该是“ DONE”
在此阶段如何避免捕获断言?
尤其是在订单1中出现断言错误
这就是我所做的...
def calculate_price(price, order):
final_list = []
# Iterating through each dictionary key.
for key, order_value in order.items():
# Splitting on whitespace, taking the first result.
first_word = key.split()[0]
# Initiating condition to compare key similarities.
if first_word in price:
# Matching dict keys successful.
price_value = price[first_word]
# Multiplying key-pair values of two matched keys.
individual_price = (order_value*price_value)
final_list.append(individual_price)
new = sum(final_list)
if new >= 101:
order3 = new - (new*0.10)
elif new >= 51:
order1 = new - (new*0.05)
order1 = int(order1)
else:
order2 = new
price = {'book': 10.0, 'magazine': 5.5, 'newspaper': 2.0}
order1 = {'book': 10}
order2 = {'book': 1, 'magazine': 3}
order3 = {'magazine': 5, 'book': 10}
assert(95 == calculate_price(price, order1))
assert(26.5 == calculate_price(price, order2))
assert(114.75 == calculate_price(price, order3))
print("Done")
非常感谢您的建议和帮助。谢谢
答案 0 :(得分:1)
https://www.tutorialspoint.com/python/assertions_in_python.htm
当遇到断言语句时,Python会评估附带的表达式,希望它是正确的。如果表达式为假,Python会引发AssertionError异常。
在您的代码中,该函数求值为false,因为您的calculate_price函数返回一个None
值。
assert
语句中隐含的约定是,该函数将返回int或float,即从输入到函数的单个订单计算出的成本值。
答案 1 :(得分:0)
试试这个:
还添加了用于在价格字典中不存在 order 中的 item 时引发 keyerror 的代码。
def calculate_price(price, order):
count = 0
for i in order:
if i in price:
count += (price[i] * order[i])
else :
raise KeyError('Key not found')
if 50 <= count <= 100:
count *= 0.95
elif count > 100:
count *= 0.90
return count
price = {'book': 10.0, 'magazine': 5.5, 'newspaper': 2.0}
order1 = {'book': 10}
order2 = {'book': 1, 'magazine': 3}
order3 = {'magazine': 5, 'book': 10}
assert(95 == calculate_price(price, order1))
assert(26.5 == calculate_price(price, order2))
assert(114.75 == calculate_price(price, order3))
print("Done")