全局名称未定义错误



我的折扣变量不断收到错误。 名称错误:未定义全局名称"折扣"。 请查看我的代码并帮助我。我根本不想修改函数的参数。

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"),"nt","Discount    $",format(disc,"10.2"),"nt","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()
如果要

在多块作用域中访问discount,则必须将其声明为全局。

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

您从未在calctotal中定义过discount(全局范围内也没有)。将结果从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"),"nt","Discount    $",format(disc,"10.2"),"nt","Amount Due $",format (due, "10.2"),sep="")

如果我们看一下这段代码

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"),"nt","Discount    $",format(disc,"10.2"),"nt","Amount Due $",format (due, "10.2"),sep="")

discountdicount(我假设错别字)都没有在calctotal()中声明。下面应该解决 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"),"nt","Discount    $",format(disc,"10.2"),"nt","Amount Due $",format (due, "10.2"),sep="")

编辑:虽然discount成为全局变量肯定是一种方法,但一般来说,我建议不要将变量设为全局变量,除非您有充分的理由。 例如 - 如果应用的折扣将受到外部函数的影响,并且您希望它也在finddiscount()中进行更改,那么全局变量将很好地工作。 但是,在此方案中,您将在finddiscount()中创建所有可能的discount值,并且使用赋值更有意义。

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

相关内容

  • 没有找到相关文章

最新更新