Modules in Python are simply files containing Python definitions, functions, and statements. Libraries, on the other hand, are collections of modules that provide functionalities to perform various tasks without writing code from scratch. Importing these modules or libraries allows users to leverage these pre-written codes.
To use a module in your program, it must first be imported.
import
statementUsing the import
keyword, you can load a module into your script.
import math
print(math.sqrt(16)) # Outputs: 4.0
from...import
statementAllows you to import specific attributes or functions from a module.
from datetime import date
print(date.today()) # Outputs current date
import...as
statementAllows you to provide a shorthand alias for the module.
import numpy as np
array = np.array([1, 2, 3])
Python comes with a vast standard library, some of which include:
datetime
Provides functionalities to handle dates and time.
from datetime import datetime
now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S'))
os
Provides a way of using operating system-dependent functionality.
import os
print(os.getcwd()) # Outputs the current working directory
sys
Allows access to some variables used or maintained by the interpreter.
import sys
for path in sys.path:
print(path)
Beyond the standard library, there are thousands of third-party libraries. Some notable ones include:
numpy
A library for the Python programming language, adding support for large, multi-dimensional arrays and matrices.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr))
pandas
Offers data structures and operations for manipulating numerical tables and time series.
import pandas as pd
data = {'Name': ['John', 'Anna'], 'Age': [28, 22]}
df = pd.DataFrame(data)
print(df)
requests
A simple HTTP library for Python.
import requests
response = requests.get('https://www.example.com')
print(response.text)
While Python’s standard library comes pre-installed, third-party libraries typically need to be installed using package managers like pip
.
pip install requests
You can create your own module by saving your code as a .py
file. This file can then be imported into other scripts.
my_module.py
def my_function():
return "Hello from my module!"
main.py
import my_module
print(my_module.my_function()) # Outputs: Hello from my module!
Modules and libraries are fundamental to Python development. They promote code reusability and help you build applications efficiently. Whether you’re using Python’s extensive standard library, tapping into the vast ecosystem of third-party packages, or creating your own modules, understanding how to import and utilize modules is a critical skill for every Python developer.