2014-10-01 107 views
0

我似乎無法得到這個,我只是不理解如何在模塊之間傳遞參數。當然,這對我來說似乎很簡單,但也許我只是沒有得到它,我對python非常陌生,但有編程經驗。Python傳遞參數模塊

def main(): 

    weight = input("Enter package weight: ") 

    return weight 

def CalcAndDisplayShipping(weight): 

    UNDER_SIX = 1.1 
    TWO_TO_SIX = 2.2 
    SIX_TO_TEN = 3.7 
    OVER_TEN = 3.8 

    shipping = 0.0 

    if weight > 10: 
    shipping = weight * OVER_TEN 
    elif weight > 6: 
    shipping = weight * SIX_TO_TEN 
    elif weight > 2: 
    shipping = weight * TWO_TO_SIX 
    else: 
    shipping = weight * UNDER_SIX 

    print ("Shipping Charge: $", shipping) 


main(CalcAndDisplayShipping) 

當我運行此我得到:輸入包裝重量:(NUM)類型錯誤:unorderable類型:功能()> int()函數

誰能給我講解一下?

+0

我沒有看到在這段代碼中的任何地方使用python模塊?另外,這段代碼會給出一個完全不同的錯誤,因爲main()被定義爲不接受任何參數,但是你傳遞了一個(可調用的)參數。 – TML 2014-10-01 04:05:33

+0

問題的原因是在Python 3中'input()'返回一個字符串。這在Python 2中不是問題。您應該指出您正在使用Python 3,以便可以考慮這些細微差異。我用'python-3.x'標記了這個問題。 – mhawke 2014-10-01 04:26:55

回答

1

有一件事是在Python中沒有必要爲主。還有一種方法可以做到這一點,就是這樣做。

你真的需要主嗎?

import os 


def CalcAndDisplayShipping(weight): 

    UNDER_SIX = 1.1 
    TWO_TO_SIX = 2.2 
    SIX_TO_TEN = 3.7 
    OVER_TEN = 3.8 

    shipping = 0.0 

    if weight > 10: 
     shipping = weight * OVER_TEN 
    elif weight > 6: 
     shipping = weight * SIX_TO_TEN 
    elif weight > 2: 
     shipping = weight * TWO_TO_SIX 
    else: 
     shipping = weight * UNDER_SIX 

    print ("Shipping Charge: $", shipping) 

weight = float(input("Enter package weight: ")) 

CalcAndDisplayShipping(weight) 
0

我認爲你的意思是這樣的:

CalcAndDisplayShipping(main()) 

這將調用main(),並通過它的返回值作爲參數傳遞給CalcAndDisplayShipping()

0
def CalcAndDisplayShipping(weight): 

    UNDER_SIX = 1.1 
    TWO_TO_SIX = 2.2 
    SIX_TO_TEN = 3.7 
    OVER_TEN = 3.8 

    shipping = 0.0 

    if weight > 10: 
     shipping = weight * OVER_TEN 
    elif weight > 6: 
     shipping = weight * SIX_TO_TEN 
    elif weight > 2: 
     shipping = weight * TWO_TO_SIX 
    else: 
     shipping = weight * UNDER_SIX 

    print ("Shipping Charge: $", shipping) 

if __name__ == '__main__': 

    weight = float(input("Enter package weight: ")) 
    CalcAndDisplayShipping(weight) 

如果您正在運行使用Python解釋器像蟒蛇 這script_name.py腳本,__name__變量值將是'__main__'

如果您要將此模塊導入其他模塊__name__不會是__main__並且它不會執行主要部分。

所以你可以使用這個功能,如果你想做任何事情,而你作爲一個單獨的腳本運行這個模塊。

如果您將模塊作爲單獨的腳本運行,此'if條件'僅適用。

+0

如果您將此腳本作爲單個腳本運行__name__變量 – 2014-10-01 04:27:28

+0

如果您正在使用python解釋器(如python script_name.py)運行此腳本,__name__variable值將爲'__main__'。如果您將此模塊導入其他模塊,__name__將不會是__main__,並且它不會執行__main__部分。因此,如果您想在將此模塊作爲單獨腳本運行時執行任何操作,則可以使用此功能。 – 2014-10-01 04:31:26

+0

謝謝你的建議。我編輯過它。 – 2014-10-01 05:07:54