Python Modules
A module is a Python file containing functions, classes, and variables that you can reuse in other programs. Modules help you organize code, avoid repetition, and use the thousands of libraries Python offers — from math and random to pandas and TensorFlow.
What is a Module?
Every .py file is a module. Python comes with hundreds of built-in modules like math, random, datetime, and os — plus millions more installable via pip.
Importing a Module
# Import entire module
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
Importing Specific Items
# Import only what you need
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.14159...
Import with Alias
import math as m
print(m.sqrt(49)) # 7.0
import pandas as pd
import numpy as np
# Common convention in data science
Common Built-in Modules
math
import math
print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.factorial(5)) # 120
print(math.pi) # 3.14159...
random
import random
print(random.randint(1, 10)) # Random 1-10
print(random.choice(["a", "b", "c"])) # Random choice
print(random.random()) # 0.0 to 1.0
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)
datetime
from datetime import datetime, date
now = datetime.now()
print(now) # Full timestamp
print(date.today()) # Today's date
print(now.strftime("%d-%m-%Y %H:%M")) # Formatted
os
import os
print(os.getcwd()) # Current directory
print(os.listdir(".")) # Files in current dir
# os.mkdir("new_folder") # Create folder
Creating Your Own Module
Save these as mymodule.py:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
PI = 3.14159
Now use it from another file in the same folder:
# main.py
import mymodule
print(mymodule.greet("Ankit")) # Hello, Ankit!
print(mymodule.add(5, 3)) # 8
print(mymodule.PI) # 3.14159
Using __name__ == "__main__"
This is a Python idiom that lets a module be both importable and runnable as a script.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
# This only runs if the file is executed directly,
# NOT when imported as a module
print("Running as main script")
print(greet("Varanasi"))
Why __name__ == "__main__"? When Python runs a file directly, __name__ is set to "__main__". When imported, __name__ is the module's name. This check lets you write test code that only runs when executed directly — great for debugging without breaking imports.
Installing External Modules (pip)
Python Package Index (PyPI) has 500,000+ packages. Install any with pip.
# In the terminal
pip install requests
pip install pandas
pip install django
# List installed packages
pip list
# Uninstall
pip uninstall requests
Popular External Packages
- requests — HTTP requests (APIs)
- pandas — Data manipulation
- numpy — Numerical computing
- matplotlib — Data visualization
- django / flask — Web development
- beautifulsoup4 — Web scraping
- tensorflow / pytorch — AI and ML
Packages vs Modules
- Module — a single .py file
- Package — a folder containing multiple modules, plus a special
__init__.pyfile
# Package structure
mypackage/
├── __init__.py
├── module1.py
└── module2.py
# Import from a package
from mypackage import module1
Real-World Example — Student Report
# report.py
from datetime import date
import random
def generate_roll_number():
return f"ADA{random.randint(1000, 9999)}"
def report_header():
return f"AI Developers Academy — Report ({date.today()})"
# Use it
print(report_header())
print("Roll Number:", generate_roll_number())
Best Practices
- Import only what you need — avoid
from module import *. - Group imports at the top: standard library first, then third-party, then your own.
- Use virtual environments (
venv) for each project. - Read the docs before using a new module.
Create a module maths.py with functions add, subtract, multiply, and divide. Then create a main.py that imports your module and tests all four functions with different inputs. Add an if __name__ == "__main__" block in maths.py that runs a quick self-test.
Quick Revision
- A module is a .py file with reusable code.
- Import with
import moduleorfrom module import x. - Aliases:
import pandas as pd. - Common built-ins:
math,random,datetime,os. - Install external modules with
pip install. - Use
__name__ == "__main__"for runnable modules. - Package = folder with
__init__.py+ modules.
Interview Questions
Q: Difference between a module and a package?
A: A module is a single .py file. A package is a folder containing multiple modules plus an __init__.py file that tells Python it's a package.
Q: What does if __name__ == "__main__" do?
A: It checks if the file is being run directly (as the main program) or imported as a module. If run directly, __name__ equals "__main__", and the block executes. If imported, the block is skipped — useful for testing without side effects.
Q: Difference between import module and from module import x?
A: import module imports the whole module — you access its contents with module.x. from module import x imports only x directly — you use x without the prefix. Use the second for brevity, the first for clarity.
Q: Why avoid from module import *?
A: It imports everything, potentially overriding your own names and making the code harder to debug. Always import explicitly — it's clearer and safer.
Q: What is pip?
A: pip is Python's package installer. It downloads and manages third-party libraries from the Python Package Index (PyPI). Use pip install package_name to install any package.
Want to Master Python?
Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.