【问题标题】:How to solve Unbound Local error in my conditional block如何解决我的条件块中的未绑定本地错误
【发布时间】:2020-07-22 20:21:16
【问题描述】:

我需要查找订单的折扣 我使用以下代码将订单号的字符串输入到字典中,然后使用 sum() 来查找订单的总数 但是,如果有 one-1 和 one-3 和(one-4 或 one-5 或 one-6),我希望有优惠折扣 但是在条件块之后,当我想将它相乘时,我收到了一个未绑定错误

def compute_cost(order):
"""
    Function 2: compute_cost(order)
    Parameters: order (String)
    Return: Final cost of order
"""
numcount = {}
orderlist = map(int, order)
for i in orderlist:
    if numcount.get(i):
        numcount[i] += 1
    else:
        numcount[i] = 1
for i in numcount:
    if i == 1:
        numcount[i] = numcount[i]*4.25
    elif i == 2:
        numcount[i] = numcount[i]*2.50
    elif i == 3:
        numcount[i] = numcount[i]*2.00
    elif i == 4:
        numcount[i] = numcount[i]*1.25
    elif i == 5:
        numcount[i] = numcount[i]*1.50
    elif i == 6:
        numcount[i] = numcount[i]*1.75
    elif i == 7:
        numcount[i] = numcount[i]*3.75
    else:
        return print("Your order has a number outside of the range (1:7)")
    order_total = sum(numcount.values())
    if(numcount[1] == 1 and
       numcount[3] == 1 and
       (numcount[4] == 1 or
       numcount[5] == 1 or
       numcount[6] == 1)):
        discount1 = 0.20
    order_total1 = order_total*discount1
return order_total1

请帮帮我 感谢您的时间和精力

编辑 如果您有更好的方法让我找到值并将它们保存在字典中,我也愿意接受建设性的批评

【问题讨论】:

  • 您能否举例说明如何调用compute_cost() 函数,然后说明预期结果应该是什么?

标签: python-3.x function dictionary conditional-statements unbound


【解决方案1】:

根据输入,numcount-dict 可能有也可能没有所有的键。

案例 1:UnboundLocalError

当使用compute_cost('12323123') 调用函数时,numcount-dict 变为:

{1: 2, 2: 3, 3: 3}

if 语句首先检查是否为 numcount[1] == 1,其结果为 False。因此 whole 表达式是 False 并且 Python 甚至不需要(需要)检查其余部分。 (这称为短路评估。)

因为 if 语句的计算结果为 False,所以根本没有设置 discount1,所以你得到了 UnboundLocalError: local variable 'discount1' referenced before assignment

解决方案: 添加一个 else 子句,当条件为 False 时将 discount1 设置为 1(= 无折扣):

if (numcount[1] == 1 and numcount[3] == 1 and (numcount[4] == 1 or
    numcount[5] == 1 or numcount[6] == 1)):
    discount1 = 0.20
else:
    discount1 = 1

案例 2:KeyError

现在,当使用compute_cost('32235664') 调用函数时,numcount-dict 变为:

{3: 2, 2: 2, 5: 1, 6: 2, 4: 1}

if 语句首先检查是否为numcount[1] == 1,但该键不存在,因此 Python 生成一个KeyError。根据您的输入以及 Python 需要评估if 语句的程度,您可能会得到KeyError

解决方案: 确保 numcount-dict 包含从头开始的所有键。您已经知道 dict 必须有多少项,因为您将输入限制在范围 (1:7) 内。因此,您可以将字典初始化为:

numcount = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}

编辑:有更好的方法吗?

当然有,几乎总是有更好的方法:

prices = {'1':4.25, '2':2.50, '3':2.00, '4':1.25, '5':1.50, '6':1.75, '7':3.75}
orders = '12323456'

total = sum(prices[order] for order in orders)
if (all(orders.count(type) >= 1 for type in '13') and           # multiple ANDs with 'all'
    any(True for type in '456' if orders.count(type) >=1)):     # multiple ORs with 'any'
    discount = 0.2
else:
    discount = 1
print('Order value: {}\nDiscount: {}\nOffer: {:.2f}'.format(total, discount, discount * total))

您现在可以轻松扩展价格字典或折扣条件。我假设折扣的条件是订购了至少一件物品,而不是完全一件。因此我使用了>=1,如果需要完全一个,你可以将其更改为==1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2014-10-02
    • 2015-06-21
    相关资源
    最近更新 更多