2012-08-28 25 views
-2

我有一個我之前編寫的腳本,現在正在嘗試創建一個主頁來運行此腳本和其他腳本。我知道我必須把它變成一個函數,然後在需要時調用它,但我在函數部分遇到了一些麻煩。任何幫助和建議,不勝感激。以下是我參考的腳本。如何將腳本變成函數

#A Python math script 
a = float(raw_input("Enter the first number: ")) 
b = float(raw_input("Enter the second number: ")) 

print "Your answer is: ",(a*b) 
+2

你真的應該看看:http://docs.python.org/release/1.5.1p1/tut/functions.html –

+1

或者當前的文檔:http://docs.python.org/release/2.7/tutorial/controlflow的.html#德罰函數(v1.5文檔已超過12年!) – dsh

+0

你是對的。我意外地發佈了一個非常過時的文檔鏈接。 ;) –

回答

5

如果你需要的是讓這個代碼到一個腳本那麼這個保存到一個文件中說multiply.py

在這個文件中,可以有例如:通過包括這條巨蟒multiply.py

您也可以爲導入的模塊,這樣的:

def main(): 
    a = float(raw_input("Enter the first number: ")) 
    b = float(raw_input("Enter the second number: ")) 

    print "Your answer is: ",(a*b) 

main() 

,那麼你可以通過調用這個該行檢查該模塊是否作爲主程序執行。因此,如果它被另一個模塊導入,它將不會運行。

if __name__ == '__main__': 
    main() 
+0

謝謝,這就是我一直在尋找。 – user1630407

0

你想要什麼功能?如果你希望它仍然需要從提示輸入和輸出,你可以做

def myfunc(): 
    a = float(raw_input("Enter the first number: ")) 
    b = float(raw_input("Enter the second number: ")) 

    print "Your answer is: ",(a*b) 
-1

它看起來像我希望能夠通過web瀏覽器使您的功能的結果,並可能以相同的方式發送查詢。

如果是這種情況,您可以開始here

-1

如果由於一些未知的原因,你不能把它改寫爲函數,如由其他人,你可以做

一個Python腳本數學

#script.py 
a = float(raw_input("Enter the first number: ")) 
b = float(raw_input("Enter the second number: ")) 

print "Your answer is: ",(a*b) 

另一個腳本

def func(): 

    execfile("script.py") 
相關問題