如何解决我的条件块中的未绑定本地错误

How to solve Unbound Local error in my conditional block

我需要找到订单的折扣 我使用以下代码将订单号的字符串输入到字典中,然后使用 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

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

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

根据输入,numcount-dict 可能包含也可能不包含所有键。

情况一: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

案例二: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