2014-02-22 32 views
-3

我想給量返回的基於家庭收入和這段代碼有什麼問題?它給出了一個錯誤

當我運行它,它說,孩子的數量:

Traceback (most recent call last): line 24, in main() line 5, in main print("Amount returned: ", amount(returned)) NameError: global name 'returned' is not defined >>> –

def main(): 
    income = int(input("Please enter the annual household income: ")) 
    children = int(input("Please enter the number of children for each applicant: ")) 

    print("Amount returned: ", amount(returned)) 


def amount (returned): 
    if income >= 30000 and income < 40000 and children >= 3: 
     amnt = (1000 * children) 
     return amnt 

    elif income >= 20000 and income < 30000 and children >= 2: 
     a = (1500 * children) 
     return a 

    elif income < 20000 : 
     r = (2000 * children) 
     return r 

    else: 
     return "error" 

main() 
+4

**它給了什麼**錯誤?它應該做什麼?不要只是把代碼轉儲給我們,*解釋你想要我們做什麼*。 –

+0

當我運行它,它說:回溯(最近通話最後一個): 線24,在 的main() 5號線,在主 打印( 「額返回:」 量(返回)) NameError:全局名稱'returned'未定義 >>> – user3341166

+2

您是否定義了'returned'? – beerbajay

回答

2

當你這樣做:

amount(returned) 

...你調用的函數amount,你是給它的變量returned的值。在你的代碼中,你沒有定義變量returned,這就是你得到錯誤的原因。

寫你想要做什麼正確的方法是在incomechildren傳遞 - 這成爲輸入你的函數 - 然後打印什麼函數返回:

print("Amount returned: ", amount(income, children)) 

這意味着你必須重新定義函數接受incomechildren作爲輸入:

def amount(income, children): 
    ... 

如果你真的需要一個名爲returned變量,你將其設置爲福的結果nction:

returned = amount(income, children) 
print("Amount returned: ", returned) 
+0

我將如何定義返回的變量?我將它定義爲什麼? – user3341166

+0

我已更新我的答案以解決該問題。 –

+0

好的,非常感謝你! – user3341166

0

@ user3341166我以爲你是學習編碼,你有概念的錯誤,照顧好你的問題,或者你會感到失望在這個網站,記得問聰明的問題,我的意思是,讀谷歌和每次出現錯誤時,粘貼錯誤,但首先讀取錯誤,在錯誤描述中有一段時間是解決方案

您的錯誤在函數上定義,當您定義函數時,您還定義輸入變量或沒有輸入,你的情況下,你需要兩個輸入來傳遞收入和孩子,否則,你的功能將不知道什麼工作。

如果你檢查你的函數,你使用了兩個變量「income and children」,但是這個變量被定義爲函數外,你需要一種方法將它們傳遞給函數,然後你需要創建函數參數。

我希望你能理解我的小介紹。好運

def main(): 
    income = int(input("Please enter the annual household income: ")) 
    children = int(input("Please enter the number of children for each applicant: ")) 

    print("Amount returned: ", amount(income, children)) 


def amount (income, children): 
    if income >= 30000 and income < 40000 and children >= 3: 
     amnt = (1000 * children) 
     return amnt 

    elif income >= 20000 and income < 30000 and children >= 2: 
     a = (1500 * children) 
     return a 

    elif income < 20000 : 
     r = (2000 * children) 
     return r 

    else: 
     return "error" 

if __name__ == '__main__': 
    main()