蟒蛇模塊

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

示例:

# 簡單模塊,calc.py


def add (x, y):

return (x + y)


def 減 (x, y):

return (x - y)

import 語句
我們可以使用任何 Python 源文件作為通過在另一個源 Python 文件中執行導入語句來導入模塊。
當解釋器遇到導入語句時,如果該模塊存在於搜索路徑中,它會導入該模塊。搜索路徑 —這是解釋器用來導入模塊的目錄列表。例如,要導入 calc.py 模塊,我們需要在腳本頂部放置以下命令:


# calc. py importer

import calc

print add ( 10 , 2 )

輸出:

12 

導入語句

Python from 語句允許您從模塊導入某些屬性。 from .. import .. 語法如下:


# importing sqrt() and factorial from


code>
# 數學模塊

from math import sqrt, factorial


#如果我們只是“導入數學”那麼
# math. sqrt (16) and math.factorial ()
# 必填。

print sqrt ( 16 )

print 階乘( 6 )

輸出:

4.0 720 

dir()函數
dir()內置- in 函數返回一個排序的字符串列表,其中包含模塊定義的名稱。該列表包含模塊中定義的所有模塊、變量和函數的名稱。


# 將內聯模塊導入隨機

import 隨機

打印 目錄 (math)

輸出:

[`BPF`,`LOG4`, `NV_MAGICCONST`、`RECIP_BPF`、`Random`、`SG_MAGICCONST`、`SystemRandom`、`TWOPI`、`WichmannHill`、`_BuiltinMethodType`、`_MethodType`、`__all__`、`__builtins__`、`__doc__`、`__file__ `,`__name__`,`__package__`,`_acos`,`_ceil`,_e _cos`,`,`_exp`,`_hashlib`,`_hexlify`,`_inst`,`_log`,`_pi`,`_random `,`_sin`,`_ sqrt`,`_test`,`_test_generator`,`_urandom`,`_warn`,`betavariate`,`choice`,`除法`,`expovariate`,`gammavariate`,`gauss`, ` 獲取隨機數`,`getstate`,` jumpahead`,`lognormvariate`,`normalvariate`,`paretovariate`,`randint`,`random`,`randrange`,`sample`,`seed`,`setstate`,`shuffle`, ` triangular`, `uniform`, `vonmisesvariate`, `weibullvariate`] 

說明內置 Python 模塊的代碼片段:

# 內置數學模塊的導入

import math


# 使用平方根函數 ( sqrt)
# 在數學模塊中

print math. sqrt ( 25 )


#使用pi函數包含在數學模塊中

print math.pi


# 2 弧度 = 11 4.59度

打印 math.degrees( 2 )


# 60 度 = 1.04 弧度

print math.radians ( 60 )


# 正弦 2 弧度

print math.sin ( 2 )


# 餘弦 0.5 弧度

print math.cos ( 0.5 )


# 0.23 弧度正切

print math.tan ( 0.23 )


# 1 * 2 * 3 * 4 = 24

print math.factorial ( 4 )



# 將內聯模塊導入隨機

import random


# 打印一個從0到5的隨機整數

print random.randint( 0 , 5 )


# 打印一個從 0 到 1 的隨機浮點數

print random.random ()


# 0 到 100 的隨機數

print random.random() * 100


List = [ 1 , 4 , True , 800 , "python" , 27 , "hello" ]

< br> # 使用隨機模塊中的pick函數來選擇
# 從一個集合中隨機元素,例如一個列表

print random.choice ( List )


# import inline datetime module

import datetime

from datetime import 日期

導入 時間


# 返回自
# Unix Epoch Jan 1, 1970 以來的秒數

print time.time()


# 轉換次數日期對象的秒數

pr int date.fromtimestamp ( 454554 )

輸出:

5.0 3.14159265359 114.591559026 1.0471975512 0.909297426826 0.87758256189 0.214 3943360153. 88.4917616788 真 1461425771.87 1970-01-06 
amp-youtube data-videoid = nfYZL-uFm-c 佈局 = 響應寬度 = 665 高度 = 374>

這篇文章由 Gaurav Shrestha 留下。如果您發現有問題或想分享有關上述主題的其他信息,請發表評論。如果你喜歡 Python.Engineering 並願意做出貢獻,你也可以寫一篇文章並郵寄到 [email protected]。在 Python.Engineering 主頁上查看您的文章並幫助其他極客。