Import entire module
import math
result = math.sqrt(16) # 4.0
print(math.pi) # 3.14159...
Import specific names
from math import sqrt, pi
result = sqrt(16) # No need for math. prefix
print(pi)
Import with alias
import numpy as np
import pandas as pd
# Use shorter names:
array = np.array([1, 2, 3])
df = pd.DataFrame(data)
Import all (not recommended)
from math import * # Imports everything
# Can use without prefix:
result = sqrt(16)
print(pi)
# Problem: pollutes namespace, unclear where names come from
Import from your own files
# If you have a file called utils.py:
# utils.py:
def helper_function():
return "Hello"
# main.py:
from utils import helper_function
helper_function()
Standard library modules
Python comes with many useful modules:
os— operating system interfacesys— system-specific parametersdatetime— date and time handlingjson— JSON data handlingrandom— random number generation