What Are Libraries?
A library is a collection of functions that can be added to your Python code and called as necessary, just like any other function. There is no reason to rewrite code that will perform a standard task. With libraries, you can import pre-existing functions and efficiently expand the functionality of your code.
Some examples of popular libraries and their functionalities:
Requests: an elegant and simple HTTP library for Python, commonly used for REST API calls. (See my other course, Build Your Web Projects With REST APIs, to learn more! 😉 )
Beautiful Soup: a library for pulling data out of HTML and XML files.
Pandas: a fast, powerful, and easy-to-use open-source data analysis and manipulation tool.
There are thousands of Python libraries that you can use in your Python code!
Install Libraries Using Pip
Pip is a Python package manager.
What’s a package manager?
A package manager is a tool that allows you to install and manage additional libraries through your terminal. Pip comes ready to go with a Python installation, so you’re already good to go!
To install a package using pip in your terminal, we use the following pattern:
pip install <name-of-package>
To view the packages already installed, you can type the following:
That will print a list of all the existing libraries, or dependencies, to your terminal.
Check out the screencast below to learn more about installing and viewing your Python packages using pip!
Import Libraries in Your Code
To import library functionality into your code, use the keyword
import. (Shocker, right? 😄 )
import keyword at the top of your code file, you can import certain library functions or the entire library at once. For example, to import the entire requests library, you must first install requests using your terminal with
pip install requests . Then you can write the following code in your text editor:
Now to call the
get() function in the requests library, write:
If you want to import just one function named
get from the requests library, write the following:
from requests import get
Now you don’t need to type requests before
get() because the method itself has already been imported.
A library is a collection of existing functions that can be used in your code.
Pip is a Python package manager that lets you install and manage your external libraries.
The import keyword lets you import entire libraries or specific library functions into your code.
Nice, you’ve learned how to import libraries using pip! Next, you’ll learn how to use these libraries to extract web data. Exciting stuff, right?