2014-02-18 158 views
1

我一直在使用我的折扣變量獲取錯誤。名稱錯誤:未定義全局名稱'折扣'。請看看我的代碼並幫助我。我不想修改函數的參數。全局名稱未定義錯誤

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() 
+0

好吧我加了謝謝你 – user3285386

回答

3

如果您想要在多塊範圍內訪問它,則必須聲明discount爲全局。

discount = 0 

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

當我試着回去宣佈它是一個全球性的,它給了我錯誤名稱'折扣'在全球聲明前分配 – user3285386

+0

你可以發佈顯示你的原始折扣聲明的代碼'? – jeremyjjbrown

+0

@jeremyjjbrown我不認爲'折扣'應該是一個全球性的。實際上有一個函數調用來在拋出錯誤的函數中計算它。 – Nabla

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"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="") 
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也不dicount(我該塊假設錯字)已在calctotal()中聲明。下面要解決夜發出

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()中更改,那麼全局變量將很好地工作。但是,在這種情況下,您將在finddiscount()內創建discount的所有可能值,並且使用賦值更有意義。

全局變量的問題在於,您可能會意外地將它們重新分配給您不打算執行的操作,並且如果無緣由地完成命名空間,它可能會造成混亂。

相關問題