Working with Libraries
Working with Libraries
As we’ve seen in our Functions and Modularity lesson, breaking code into reusable pieces makes programming more efficient. But what if someone else has already written code that solves your problem? That’s where libraries come in!
What is a Library?
A library is a collection of pre-written code that helps you perform common tasks without having to write everything from scratch. Libraries save time and reduce errors by providing tested and optimized functionality.
For example, instead of writing your own code to generate random numbers, you can use a library that already provides this feature.
Importing Libraries
Most programming languages allow you to import libraries to use their functions.
Python Example: Using the math
Library
import math
print(math.sqrt(25)) # Outputs: 5.0
print(math.pi) # Outputs: 3.141592653589793
JavaScript Example: Using Math
console.log(Math.sqrt(25)); // Outputs: 5
console.log(Math.PI); // Outputs: 3.141592653589793
In Python, we explicitly import the math
module. In JavaScript, the Math
object is built-in, so no import is needed.
Installing External Libraries
Some libraries are built-in, meaning they come with the programming language. Others need to be installed separately.
Installing a Library in Python
Python uses a package manager called pip
to install libraries.
pip install requests
Now you can use the requests
library to fetch data from the internet:
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # Outputs: 200
Installing a Library in JavaScript (Node.js)
JavaScript uses npm
(Node Package Manager) to install libraries.
npm install axios
Now you can use axios
to fetch data:
const axios = require("axios");
axios.get("https://api.github.com").then((response) => {
console.log(response.status);
});
Finding the Right Library
There are thousands of libraries available! Here’s where to find them:
- Python: PyPI (Python Package Index)
- JavaScript: npm (Node Package Manager)
When choosing a library, consider:
- Popularity – More users usually mean better support.
- Documentation – Good libraries have clear guides and examples.
- Compatibility – Ensure it works with your project.
Why Use Libraries?
- Saves time – Avoid reinventing the wheel.
- Reduces errors – Use battle-tested code.
- Expands functionality – Work with data, graphics, networking, and more.
Summary
- Libraries provide reusable code to make programming easier.
- You can import built-in libraries or install external ones.
- Use package managers like
pip
(Python) ornpm
(JavaScript) to install libraries. - Always check documentation to learn how to use a library effectively.
Next Steps
Try using a library in your next project! Start by exploring the built-in libraries in your language and experiment with installing new ones.
Have a favorite library? Share it in the comments!
Happy coding!