Working with External Libraries
Overview
Libraries extend Python's core features to handle specialized tasks like math, data analysis, and graphics. You'll learn how to import, install, and explore external libraries such as math, requests, and matplotlib, expanding Python's capabilities for your projects.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Built-in vs external libraries: The difference between libraries that come with Python and those you install.
- Installing libraries: How to use pip to install external libraries.
- Importing libraries: Different ways to import and use library functions.
- Popular libraries: Common external libraries and what they do.
- Library documentation: How to find and use library documentation.
Built-in vs External Libraries
Python comes with many built-in libraries like math, random, and datetime. But for specialized tasks, you'll need external libraries that must be installed first.
Built-in Libraries
Come with Python, work immediately, examples: math, random, datetime, os
External Libraries
Need to install with pip, examples: requests, matplotlib, pandas, numpy
Installing External Libraries
Use pip (Python's package installer) to install external libraries:
# In your terminal/command prompt:
pip install requests
# Or for Python 3 specifically:
pip3 install requests
pip Command
pip is Python's package manager. It downloads and installs libraries from the Python Package Index (PyPI). Always install libraries in your terminal, not in Python code!
Ways to Import Libraries
There are several ways to import libraries:
# 1. Full import
import math
result = math.sqrt(16)
# 2. Import specific functions
from math import sqrt, pi
result = sqrt(16)
# 3. Import with alias
import math as m
result = m.sqrt(16)
# 4. Import everything (not recommended)
from math import *
result = sqrt(16)
Best Practices
- Use full imports for clarity:
import math - Use specific imports to avoid namespace pollution:
from math import sqrt - Use aliases for long names:
import matplotlib.pyplot as plt - Avoid
import *- it makes code harder to read
Finding and Choosing Libraries
How to find the right library for your needs:
Search PyPI
Visit pypi.org to search for libraries. PyPI (Python Package Index) is the official repository of Python packages.
Read Documentation
Check the library's documentation to understand its features, usage examples, and requirements.
Check Popularity
Look at download counts and GitHub stars. Popular libraries are usually well-maintained and have good community support.
Read Reviews
Check GitHub issues and discussions to see if the library is actively maintained and has good support.
Installing Specific Versions
You can install specific versions of libraries:
# Install specific version
pip install requests==2.28.0
# Install latest version
pip install requests
# Upgrade existing library
pip install --upgrade requests
Popular External Libraries
Here are some commonly used external libraries and what they do:
| Library | Purpose | Installation |
|---|---|---|
requests |
Make HTTP requests to APIs and websites | pip install requests |
matplotlib |
Create charts and visualizations | pip install matplotlib |
pandas |
Data analysis and manipulation | pip install pandas |
numpy |
Numerical computing and arrays | pip install numpy |
beautifulsoup4 |
Web scraping and HTML parsing | pip install beautifulsoup4 |
flask |
Build web applications | pip install flask |
pillow |
Image processing | pip install pillow |
selenium |
Web browser automation | pip install selenium |
Library Categories
Libraries are often grouped by purpose:
- Web: requests, flask, django, beautifulsoup4
- Data Science: pandas, numpy, matplotlib, seaborn
- Automation: selenium, pyautogui, schedule
- Utilities: python-dateutil, pytz, colorama
Using Library Documentation
Learning to read library documentation is crucial:
import requests
# Basic GET request
response = requests.get('https://api.github.com/users/octocat')
# Check status code
if response.status_code == 200:
data = response.json()
print(f"Username: {data['login']}")
else:
print(f"Error: {response.status_code}")
# With error handling
try:
response = requests.get('https://api.github.com/users/octocat', timeout=5)
response.raise_for_status() # Raises exception for bad status codes
data = response.json()
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
Reading Documentation
When learning a new library:
- Start with the "Quick Start" or "Getting Started" section
- Look at code examples
- Understand the basic concepts
- Try the examples yourself
- Read the API reference for specific functions
Practice: Using Libraries
Try It YourselfTry using Python's built-in math library:
What happened? You imported the math library and used its functions. External libraries work the same way - install them with pip, then import and use them!
Summary
In this lesson, you learned:
- Built-in libraries: Come with Python, work immediately
- External libraries: Need to be installed with pip
- Import methods: Full import, specific import, aliases
- Popular libraries: requests, matplotlib, pandas, numpy
- Best practices: Use clear import statements
Remember
External libraries extend Python's power. Always check library documentation to learn how to use them. The Python community has created libraries for almost everything!
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: Libraries
What is the difference between a built-in library and an external library? Give examples of each.
Exercise 2: Importing
What are the different ways to import a library in Python? When would you use each method?