【问题标题】:How to pass assertion at this stage?在这个阶段如何通过断言?
【发布时间】:2019-03-22 07:28:59
【问题描述】:

我创建了这个遍历字典的函数。我有一个价格字典,存储了一个项目的每个价格。然后是客户订单字典,每个客户的每个订单都存储在其中。

对于客户订单中的每件商品,我将商品乘以价格, 比如……

order 1: 10 books * $10.0

在此功能结束时,如果总订单超过 100 美元,我将给予 10% 的折扣。 50 美元以上 5%,低于 50 美元无折扣。

现在,由于某些原因,我无法更改下面的断言语法。必须坚持使用其中的格式和代码,问题是我遇到了断言错误。应该是,最终输出是“DONE”

如何避免在这个阶段捕获断言?

特别是我在 order1 中遇到断言错误

这就是我所做的......

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")

非常感谢您的建议和帮助。谢谢

【问题讨论】:

  • 哪个断言失败了?
  • 这是断言顺序1
  • 所以你想关闭断言?这可以通过-o 标志来完成,即python -o myfile.py,参见here
  • 嗨 nearoo,我想结束我的代码,通过所有断言为真

标签: python python-3.x assert assertion


【解决方案1】:

试试这个:

还添加了在价格字典中不存在按顺序排列的商品时引发 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")

【讨论】:

    【解决方案2】:

    https://www.tutorialspoint.com/python/assertions_in_python.htm

    当遇到断言语句时,Python 会评估伴随的表达式,希望这是真的。如果表达式为假,Python 会引发 AssertionError 异常。

    在您的代码中,该函数评估为 false,因为您的 calculate_price 函数返回一个 None 值。

    assert 语句中隐含的约定是该函数将返回一个 int 或 float,即从函数的输入为单个订单计算的成本值。

    【讨论】:

    • 我明白了,这意味着我应该在我的函数中使用 return 语句吗? :)
    • 再次嗨,所以我在最后一个 if else 语句中放了一个 return 语句,它通过了所有断言并打印出“DONE”
    猜你喜欢
    • 2017-11-08
    • 2019-08-14
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多