全局名称未定义错误

时间:2014-02-18 03:27:37

标签: python return global-variables function

我的折扣变量一直出错。 name-error:未定义全局名称'discount'。请看看我的代码并帮助我。我根本不想修改函数的参数。

def finddiscount(quantity):
    if quantity >= 1 and quantity <= 9:
        discount = 0
    elif quantity >= 10 and quantity <= 19:
        discount = .2
    elif quantity >= 20 and quantity <= 49:
        discount = .30
    elif quantity >= 50 and quantity <= 99:
        discount = .40
    elif quantity >= 100:
        discount = .50
    return discount
def calctotal(quantity, price):
    finddiscount(quantity)
    disc = (price*quantity)*discount
    total = (price*quantity)
    due = (price*quantity)-(price*quantity)*dicount
    print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount    $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
def main():
    quantity = int(input("How many packages where purchased?"))
    price = float(input("How much is each item?"))
    calctotal(quantity, price)
main()

3 个答案:

答案 0 :(得分:3)

如果要在多块范围内访问它,则必须将discount声明为全局。

discount = 0

def finddiscount(quantity):
    ...
    global discount    # Needed to modify global copy of discount
    discount = 1

答案 1 :(得分:1)

disc = (price*quantity)*discount

您从未在discount中定义calctotal(在全局范围内也未定义)。将finddiscount(quantity)的结果分配给它。目前您正在计算折扣,但不立即将结果分配给任何变量:

def calctotal(quantity, price):
    discount = finddiscount(quantity)
    disc = (price*quantity)*discount
    total = (price*quantity)
    due = (price*quantity)-(price*quantity)*dicount
    print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount    $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")

答案 2 :(得分:0)

如果我们看一下这段代码

def calctotal(quantity, price):
    finddiscount(quantity)
    disc = (price*quantity)*discount
    total = (price*quantity)
    due = (price*quantity)-(price*quantity)*dicount
    print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount    $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")

discount中已宣布dicountcalctotal()(我假设拼写错误)。下面应该解决yoru问题

def calctotal(quantity, price):
    discount = finddiscount(quantity)
    disc = (price*quantity)*discount
    total = (price*quantity)
    due = (price*quantity)-(price*quantity)*discount
    print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount    $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")

修改 虽然使discount成为一个全局变量当然是一种方法,但总的来说,除非你有充分的理由,否则我建议不要将变量设为全局变量。例如 - 如果应用的折扣将受到外部函数的影响,并且您希望它在finddiscount()中更改,那么全局变量将很好地工作。但是,在这种情况下,您要在discount中创建finddiscount()的所有可能值,并且使用赋值更有意义。

全局变量的问题在于,您可能会意外地将它们重新分配给您不打算做的事情,如果无缘无故,它可能会混淆命名空间。