Introduction to Libraries and Packages in Python
Introduction to Libraries and Packages
Discover how to leverage external libraries and package managers to speed up development in Python.
What is a Library?
A library in Python is a collection of modules or functions that you can use in your programs without having to write them from scratch.
What is a Package?
A package is a directory that contains multiple Python modules, usually organized for a specific purpose. It may also contain a special __init__.py file to make it recognizable as a package.
Installing Packages with pip
You can use pip (Python's package installer) to install third-party libraries easily.
pip install requests
This installs the popular HTTP library requests.
Using Installed Libraries
import requests response = requests.get("https://api.github.com") print(response.status_code)
This code uses the requests library to make a GET request to GitHub's API.
Popular Libraries:
NumPy (Numerical Computing)
import numpy as np arr = np.array([1, 2, 3]) print(arr * 2)
This code creates a NumPy array and multiplies all elements by 2.
Pandas (Data Analysis)
import pandas as pd data = {"Name": ["Alice", "Bob"], "Age": [25, 30]} df = pd.DataFrame(data) print(df)
This example creates a simple data table using the pandas library.
Basic Introduction to Virtual Environments
A virtual environment allows you to manage dependencies for different projects separately, avoiding conflicts between packages.
Creating a Virtual Environment
python -m venv myenv
This creates a virtual environment named myenv.
Activating the Environment
Windows:
myenv\Scripts\activate
macOS/Linux:
source myenv/bin/activate
Deactivating the Environment
deactivate
This exits the virtual environment.