What is a module?#
A module is simply a Python file (.py) containing functions, variables and classes that you can reuse in other programs by importing it.
Python comes with a huge standard library - hundreds of ready modules for maths, dates, files, random numbers, internet, and more. ("Batteries included" is Python's motto.)
Ways to import#
| Style | Use like | When |
|---|---|---|
import math |
math.sqrt(9) |
clear where each name comes from (recommended) |
from math import sqrt |
sqrt(9) |
you use a few names often |
import numpy as np |
np.array(...) |
long module names - common conventions |
from math import * |
sqrt(9) |
avoid - pollutes your namespace, hides where names come from |
Module = पहले से लिखे हुए code की एक file, जिसे आप import करके इस्तेमाल कर सकते हैं - जैसे औज़ारों का डिब्बा (toolbox)।
import math→ पूरा toolbox ले आओ, और हर औज़ारmath.लगाकर इस्तेमाल करो (math.sqrt(16))।from math import sqrt→ toolbox से सिर्फ एक औज़ार निकाल लो, और सीधेsqrt(16)लिखो।import pandas as pd→ लंबे नाम को छोटा नाम (alias) दे दो।
Useful standard library modules#
math#
random#
Run it several times - the output changes each time.
datetime#
Common format codes: %d day, %m month, %Y 4-digit year, %H hour (24h), %M minute, %A weekday name, %B month name.
collections#
os and sys (working with the system)#
import os
print(os.getcwd()) # current folder
print(os.listdir(".")) # files in a folder
os.makedirs("reports", exist_ok=True)
print(os.path.exists("data.csv"))
import sys
print(sys.version) # Python version
Others worth knowing#
| Module | Used for |
|---|---|
json |
read/write JSON data (APIs, config files) |
csv |
read/write CSV (Excel-like) files |
time |
delays (time.sleep(2)), timing code |
statistics |
mean, median, mode, stdev |
re |
regular expressions (pattern matching in text) |
pathlib |
modern file path handling |
Exploring a module#
import math
print(dir(math)) # list everything inside
help(math.sqrt) # documentation for one function
Creating your own module#
Any .py file is a module. Suppose you create billing.py:
# billing.py
GST_RATE = 18
def add_gst(amount):
return amount + amount * GST_RATE / 100
def format_rupees(amount):
return f"Rs. {amount:,.2f}"
In another file in the same folder, e.g. main.py:
import billing
total = billing.add_gst(2500)
print(billing.format_rupees(total)) # Rs. 2,950.00
if name == "main":#
Every module has a built-in variable __name__:
- When you run the file directly →
__name__is"__main__". - When the file is imported →
__name__is the module's name ("billing").
This lets a file contain test code that runs only when executed directly:
# billing.py
def add_gst(amount):
return amount * 1.18
if __name__ == "__main__":
# runs for: python billing.py
# does NOT run for: import billing
print(add_gst(100))
if __name__ == "__main__": का मतलब है - "यह code तभी चलाओ जब यह file सीधे चलाई जाए, किसी दूसरी file में import होने पर नहीं।"
इससे आप एक ही file में functions भी रख सकते हैं और उनकी testing भी कर सकते हैं - import करने वाले program पर testing वाला code असर नहीं डालेगा। Professional Python code में यह लाइन लगभग हर main file में दिखती है।
Packages#
A package is a folder of modules. It usually contains an __init__.py file:
myshop/
├── __init__.py
├── billing.py
└── inventory.py
from myshop import billing
from myshop.inventory import check_stock
pip - installing third-party libraries#
Beyond the standard library, there are 500,000+ free packages on PyPI (pypi.org). Install them with pip in your terminal (not inside Python):
pip install requests # install
pip install pandas==2.2.2 # a specific version
pip list # what's installed
pip uninstall requests # remove
pip freeze > requirements.txt # save your project's packages
pip install -r requirements.txt # install them on another computer
Popular packages:
| Package | Purpose |
|---|---|
requests |
call websites and APIs |
pandas |
data analysis, Excel/CSV |
numpy |
fast maths on arrays |
matplotlib |
charts |
flask, django, fastapi |
web development |
openpyxl |
Excel files |
selenium |
browser automation |
Use a virtual environment for each project so package versions don't clash:
python -m venv venv
venv\Scripts\activate # Windows
source venv/bin/activate # macOS / Linux
pip install requests
The browser editor on this site runs a special build of Python (Pyodide). The standard library works, but pip install is not available here - practise pip on your own computer.
Summary#
- A module is a
.pyfile; import withimport x,from x import y, orimport x as z. - The standard library includes
math,random,datetime,collections,os,json,csvand more. - Your own
.pyfiles are modules too; packages are folders of modules. if __name__ == "__main__":runs code only when the file is executed directly.- Install third-party packages with
pip install name, ideally inside a virtual environment.