下面來創建模塊。模塊就是一個 Python 文件,類似代碼清單 15-1 中給出的文件。在一個 IDLE 編輯器窗口中鍵入代碼清單 15-1 中的代碼,把它保存為 my_module.py。
代碼清單 15-1 創建一個模塊
# this is the file "my_module.py"# we're going to use it in another programdef c_to_f(celsius): fahrenheit = celsius * 9.0 / 5 + 32 return fahrenheit
就這麼簡單!這樣就創建了一個模塊!模塊中只有一個函數,也就是 c_to_f
函數,它會把溫度從攝氏度轉換為華氏度。
接下來我們在另一個程序中使用 my_module.py。