In Python, modules are essentially code libraries containing functions, variables, and classes that you can use in your Python programs without having to rewrite them. This makes your code more organized, efficient, and reusable.
Modules can be classified into two types:
- Built-in modules
- External modules
Built-in Modules
These modules come pre-installed with Python, you don’t need to install them. You can just simply import and use them into your code. Some examples of built-in modules are:
random
(for random number generation)datetime
(for working with dates and times)math
(for mathematical operations)
Using a built-in module
To use a built-in module, simply import it at the beginning of your Python script.
Here’s an example of using the math
module:
import math
result = math.sqrt(9)
print(result) # Output: 3.0
In this example:
- You import the
math
module. - Then, you use the
sqrt()
function to calculate the square root of 9.
External Modules
These modules are third-party modules or libraries that are not included in the Python standard library. These need to be installed separately using a package manager like pip
or conda
. Some examples of external modules are:
pandas
(for data manipulation and analysis)numpy
(for numerical computations)tensorflow
(for machine learning)
Using an external module
To use an external module, you first need to install it using a package manager. Open your terminal or command prompt and run the following command:
pip install pandas
After installation, you can import and use the module in your Python script.
Here’s an example of using pandas
to read a JSON file:
import pandas
# Reading data from a json file
df = pandas.read_json('data.json') # Make sure the file exists in your project folder
print(df)
In this example:
- You install and import the
pandas
library. - You use the
read_json()
function to read a JSON file (data.json
), which should be in your project directory for this code to work.
Let’s take another example.
Open your terminal or command prompt and run the following command:
pip install numpy
After installation, you can import and use the module in your Python script as follows:
import numpy
# Using numpy to create an array
arr = numpy.array([1, 2, 3, 4])
print(arr) # Output: [1 2 3 4]
Import Aliasing
Sometimes, you’ll see developers using aliases to make module names shorter. This is helpful when a module name is long or used often.
For example:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr) # Output: [1 2 3 4]
Here, np
is just a nickname for numpy
.
Tip
You can install multiple modules at once using:
pip install pandas numpy
This saves time when you need to set up your project with multiple external libraries.
Similarly you can explore and use other modules as well by going through their documentations for usage instructions.