Ravindra BagaleCourses & study guides मराठी Track your progress

Python Modules, pip and Virtual Environments (venv) Explained for Beginners

P10.1 What Is a Module in Python and How to Import It

Why. Square roots, dates, random samples — someone already wrote and tested this code. Importing it saves time and avoids bugs.

What. A module is a Python file with ready code. A package is a folder of modules (pandas is a package).

  • import math — use as math.sqrt(16)
  • from math import sqrt — use as sqrt(16)
  • import pandas as pd — short alias

How.

Import and use

  1. Write the import at the top of your file or notebook.
  2. Call functions with module.function().
  3. Use help(module) or dir(module) to explore.

Worked example A — Three import styles.

Step 1 — What we do. We calculate a square root three ways.

Step 2 — Type and run this code.

import math
print(math.sqrt(144))

from math import sqrt
print(sqrt(144))

import math as m
print(m.sqrt(144))

Step 3 — Output you should see.

12.0
12.0
12.0

Step 4 — What it means. All give 12.0. Data scientists always write import numpy as np and import pandas as pd — the aliases are a worldwide habit.

Python next to other languages — use a library. You do not need to learn these other languages. This only shows why Python is easier to read.

Language Code
Python import math
Java import java.util.List;
JavaScript import fs from "fs";
Go import "math"

Ravindra Bagale's Tip

Put all imports in the first cell of your notebook. When you restart, one run of that cell loads everything.