Libraries and modules are essential to Python, enabling developers to reuse code,
reduce redundancy, and leverage powerful prebuilt functionalities. Python comes
with a rich standard library, and you can also install third-party libraries to extend
its capabilities.
1. What are Modules and Libraries?
A module is a file containing Python code (functions, classes, variables) that
can be imported and reused.
A library is a collection of modules packaged together for specific tasks.
Example:
A single .py file is a module, whereas libraries like NumPy or Pandas contain
multiple modules.
2. Importing Modules
Python provides the import statement to use modules in your program.
Importing a Module:
import math
print(math.sqrt(16)) # Output: 4.0
Importing Specific Functions or Variables:
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
Using Aliases:
, import math as m
print(m.pow(2, 3)) # Output: 8.0
Importing All Functions (Not Recommended):
from math import *
print(sin(pi / 2)) # Output: 1.0
3. Built-in Libraries
Python's standard library includes modules for common tasks. Here are some
popular ones:
1. os: Operating System Operations
import os
print(os.getcwd()) # Get the current working directory
os.mkdir("test_folder") # Create a new folder
os.rmdir("test_folder") # Remove the folder
2. sys: System-Specific Parameters and Functions
import sys
print(sys.version) # Python version
print(sys.argv) # Command-line arguments
3. datetime: Date and Time Operations
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Output: e.g., 2024-12-24
10:30:45
4. random: Generating Random Numbers