Python import 關鍵字



Python 的 import 關鍵字用於匯入模組。可以使用 import 匯入檔案/函式,以便從另一個模組訪問這些模組。

用法

以下是 Python import 關鍵字的用法:

import <module_name>

其中,module_name 是我們需要匯入的模組的名稱。

示例

以下是 Python import 關鍵字的基本用法:

import array
myArray = array.array('i',[1, 2, 3, 4, 5])
print(myArray)

輸出

以下是上述程式碼的輸出:

array('i', [1, 2, 3, 4, 5])

使用 'import' 關鍵字與 'from'

我們可以將 import 關鍵字與 from 一起使用來匯入模組。

示例

以下是 importfrom 一起使用的示例:

from math import sqrt, pow
# Using the imported functions
print("Square root of 99 is:", sqrt(99))  
print("7 to the power of 3 is:", pow(7, 3))

輸出

以下是上述程式碼的輸出:

Square root of 99 is: 9.9498743710662
7 to the power of 3 is: 343.0

使用 'import' 與星號 (*)

import 關鍵字不僅可以匯入特定函式,還可以使用 星號[*] 匯入模組的所有函式。要匯入模組的所有函式,請使用 import 關鍵字後跟模組名稱和 星號

示例

這裡,我們使用 import星號 匯入了 math 模組的所有函式:

from math import *
print("The exponential value of e power 0:", exp(0))
print("The gcd of 3 and 6 :",gcd(3,6))

輸出

以下是上述程式碼的輸出:

The exponential value of e power 0: 1.0
The gcd of 3 and 6 : 3

使用 'import' 關鍵字與 'as'

我們還可以將 as 關鍵字與 import 一起使用,為特定函式指定一個選定的名稱。

示例

以下是 import 關鍵字與 as 關鍵字一起使用的示例:

from array import array as arr
myArray = arr('i',[10, 20, 30, 40, 50]) 
print(myArray)

輸出

以下是上述程式碼的輸出:

array('i', [10, 20, 30, 40, 50])
python_keywords.htm
廣告