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 asmath.sqrt(16)from math import sqrt— use assqrt(16)import pandas as pd— short alias
How.
Import and use
- Write the import at the top of your file or notebook.
- Call functions with
module.function(). - Use
help(module)ordir(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.
Ravindra Bagale's Tip – मराठी
सगळे imports notebook च्या पहिल्या cell मध्ये ठेवा. Restart केल्यावर तो एक cell चालवला की सगळं load होतं.
Ravindra Bagale's Tip – हिंदी
सारे imports notebook के पहले cell में रखो. Restart के बाद वो एक cell चलाते ही सब load हो जाता है.