What is a Library?
A library is a collection of reusable functions, classes, and modules. Python comes with many built-in libraries, and you can also use external libraries created by the Python community.
Importing Built-in Libraries
import math
print(“Square root of 16 is:”, math.sqrt(16))
Output:
Square root of 16 is: 4.0
Importing with an Alias
Use as
to assign a shortcut to long library names.
import datetime as dt
today = dt.date.today()
print("Today’s date is:", today)
Output:
Today’s date is: 2025-05-24
Import Specific Parts of a Library
You can import only the functions you need.
from math import pi, pow
print("Pi is:", pi)
print("2 raised to 3 is:", pow(2, 3))
Output:
Pi is: 3.141592653589793
2 raised to 3 is: 8.0
Installing and Importing External Libraries
Libraries like pandas
, numpy
, and matplotlib
are not built-in. You need to install them using pip, Python’s package manager.
Open your terminal or command prompt and run:
pip install pandas
Once installed, you can import and use it.
import pandas as pd
data = {'Name': ['John', 'Alice'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
Output:
Installing Multiple Libraries at Once
You can install several libraries in one command:
pip install numpy matplotlib seaborn
Using try-except
with External Libraries
Handle errors if the library isn’t installed.
try:
import seaborn as sns
print("Seaborn is ready to use.")
except ImportError:
print("Seaborn is not installed.")
Output:
Seaborn is ready to use.
pip list
You’ll get a list like:
numpy 1.26.4
pandas 2.2.1
matplotlib 3.8.4
Importing Your Own Modules
Create your own .py
file and import it.
file name- abc.py
def hello(name):
return f"Hello, {name}!"
file name – main.py
import abc
print(abc.hello("Alex"))
Output:
Hello, Alex!
Common External Libraries :
Library | Purpose |
---|
pandas | Data manipulation and analysis |
numpy | Numerical computing |
matplotlib | Data visualization |
seaborn | Statistical plots |
requests | HTTP requests |
scikit-learn | Machine learning |
flask | Web development |