2015-11-18 27 views
0

這是我正在使用的代碼。我正在處理兩組代碼。當我將代碼組合到一個程序中時,它會按照它應有的方式工作。當我嘗試導入「arithemtics」模塊時,它不會定義變量。我花了很多時間試圖弄清楚這一點,我擔心這件事情非常簡單Python代碼。名稱錯誤與輸入模塊

import arithmetics 


def main(): 
    num1 = float(input('Enter a number:')) 
    num2 = float(input('Enter another number:')) 

    total(num1,num2) 
    difference(num1,num2) 
    product(num1,num2) 
    quotient(num1,num2) 

main() 

這裏是「算術」輸入模塊

def total(num1,num2): 
    total = num1 + num2 
    print(format(total, ',.1f')) 


def difference(num1,num2): 
    difference = num1 % num2 
    print(format(difference, ',.1f')) 

def product(num1,num2): 
    product = num1 * num2 
    print(product) 

def quotient(num1,num2): 
    quotient = num1/num2 
    print(quotient) 

回答

1

如果使用

import arithmetics 

你需要有資格這樣

arithmetics.total 
arithmetics.difference 
arithmetics.product 
arithmetics.quotient 

或者

函數名
from arithmetics import total, difference, product, quotient 

然後名稱可以正常的模塊中使用

第三替代

from arithmetics import * 

氣餒,因爲它不是明確的,並可能導致當有人增加了一些更名arithmetics,可能會導致衝突的神祕破損

1
import arithmetics 


def main(): 
    num1 = float(input('Enter a number:')) 
    num2 = float(input('Enter another number:')) 

    arithmetics.total(num1,num2) 
    arithmetics.difference(num1,num2) 
    arithmetics.product(num1,num2) 
    arithmetics.quotient(num1,num2) 

main() 

這是因爲功能在arithmetics模塊中,它們不能通過執行import arithmetics而全局訪問,需要使用arithmetics內的函數調用模塊名稱,後跟b y函數名稱如此arithmetics.<function>

或者你可以這樣做:

from arithmetics import * 

這將導入從arithmetics所有功能集成到你的腳本的範圍,好像他們是腳本本身中定義。

請注意,做一個from x import *(特別是這個例子中的明星)並不是最優雅或有效的做事方式,如果可能的話,嘗試從庫中只導入你需要的功能(在你的情況下,明星會工作因爲無論如何你都在使用所有的函數,但其​​他庫可能很大,你可能不需要所有的函數)。

要做到這一點,你可以這樣做:

from arithmetics import total, difference, product, quotient 
+0

反對意見是? – Torxed

+0

不知道爲什麼downvote,但是,因爲你的解決方案的作品,這是一個countervol。雖然我不得不說我不是'import *'的忠實粉絲,但我更願意只將我需要的內容導入到當前命名空間中。我可能也會使用'進口算術作爲',因爲我討厭打字:-) – paxdiablo

+0

@paxdiablo乾杯隊友,你是對的。我更喜歡從另一個模塊導入功能。我會記下它。 – Torxed