You add libraries to your Python program using the import
statement. This statement tells Python to load the desired library and make its functions and classes available for use in your code.
Using the import
Statement
Here's the basic syntax for importing libraries:
import library_name
Example:
import math
This line imports the math
library, which provides mathematical functions like sqrt
, sin
, cos
, etc.
Importing Specific Functions
You can also import specific functions or classes from a library using the from...import
syntax:
from library_name import function_name
Example:
from math import sqrt
This line imports only the sqrt
function from the math
library, allowing you to use it directly without needing to prefix it with math.
.
Renaming Libraries and Functions
You can rename imported libraries or functions using the as
keyword:
import library_name as new_name
Example:
import pandas as pd
This line imports the pandas
library and renames it to pd
, making it easier to reference in your code.
Common Libraries
Here are some common libraries used in Python:
math
: Provides mathematical functions.random
: Generates random numbers.datetime
: Works with dates and times.os
: Provides operating system interactions.sys
: Provides system-specific parameters and functions.pandas
: A powerful data analysis library.numpy
: A library for numerical computing.matplotlib
: A library for creating visualizations.
Adding Libraries to Your Project
To use libraries in your Python project, you can either:
- Install them globally: Using package managers like
pip
. - Install them locally: Within your project's virtual environment.
Conclusion
Adding libraries to your Python program is crucial for expanding its functionality and taking advantage of pre-built tools. The import
statement is the key to accessing these libraries and their powerful features.