模块 python_Python入门基础:模块基础
生活随笔
收集整理的這篇文章主要介紹了
模块 python_Python入门基础:模块基础
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模塊是一個文件(.py文件),包含變量,類定義語句和與特定任務相關的功能。預先裝有Python的Python模塊稱為標準庫模塊。
創建我們的模塊
我們將創建一個名為tempConversion.py的模塊,該模塊將值從F轉換為C,反之亦然。
# tempConversion.py to convert between# between Fahrenheit and Centigrade??# function to convert F to Cdef to_centigrade(x):??????return 5 * (x - 32) / 9.0??# function to convert C to Fdef to_fahrenheit(x):???????return 9 * x / 5.0 + 32??# constants??# water freezing temperature(in Celcius)FREEZING_C = 0.0???# water freezing temperature(in Fahrenheit)?????FREEZING_F = 32.0??????現在保存此python文件并創建模塊。導入后,該模塊可以在其他程序中使用。
導入模塊
在python中,為了使用模塊,必須將其導入。Python提供了多種在程序中導入模塊的方法:
使用導入的模塊
導入模塊后,我們可以根據以下語法使用導入模塊的任何功能/定義:
module_name.function_name()這種引用模塊對象的方式稱為點表示法。
如果我們使用導入函數from,則無需提及模塊名稱和點號即可使用該函數。
示例1:導入整個模塊:
# importing the moduleimport tempConversion??# using a function of the moduleprint(tempConversion.to_centigrade(12))??# fetching an object of the moduleprint(tempConversion.FREEZING_F)輸出:
-11.1111111111111132.0示例2:導入模塊的特定組件:
# importing the to_fahrenheit() method from tempConversion import to_fahrenheit # using the imported method print(to_fahrenheit(20)) # importing the FREEZING_C object from tempConversion import FREEZING_C # printing the imported variable print(FREEZING_C)輸出:
68.00.0Python標準庫功能
python解釋器內置了許多始終可用的功能。要使用python的這些內置函數,請直接調用函數,例如function_name()。一些內置的庫函數是:input(),int(),float()等
num = 5print("Number entered = ", num)??# oct() converts to octal number-stringonum = oct(num)?????# hex() coverts to hexadecimal number-string?????hnum = hex(num)??????????print("Octal conversion yields", onum)print("Hexadecimal conversion yields", hnum)print(num)輸出:
輸入的數字= 5八進制轉換得出0o5十六進制轉換產生0x55總結
以上是生活随笔為你收集整理的模块 python_Python入门基础:模块基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python jieba词频统计英文文本
- 下一篇: 最长不重复子串python_python