Modules and Packages in Python
In this lesson: Use and create Python modules and packages — import, from, as, __name__ and pip install — with examples. In Hindi & English.
What is a Module?
A module is a Python file full of ready-made code (functions, variables) that you can reuse. Instead of writing everything yourself, you import a module and use its tools. A package is a folder of related modules.
Ways to Import
import math # import the whole module print(math.sqrt(16)) from math import pi # import one name print(pi) import math as m # give it a short alias print(m.factorial(5))
import math→ use asmath.sqrt.from math import pi→ usepidirectly.import math as m→ short aliasm.
Useful Built-in Modules
| Module | Used For |
|---|---|
| math | sqrt, pi, factorial, pow |
| random | random numbers, choice, shuffle |
| datetime | current date and time |
| os | files and folders |
| statistics | mean, median, mode |
Program 1: Using math
import math
print("Square root of 25 :", math.sqrt(25))
print("5 factorial :", math.factorial(5))
print("Value of pi :", round(math.pi, 4))
print("2 to power 10 :", math.pow(2, 10))Program 2: Using random
import random
print("Random 1-6 :", random.randint(1, 6)) # dice roll
fruits = ["apple", "mango", "kiwi"]
print("Random fruit:", random.choice(fruits))
random.shuffle(fruits)
print("Shuffled :", fruits)randint gives a whole number in a range; choice picks one item; shuffle mixes a list. (Output changes each run.)
Program 3: Your Own Module
Any .py file can be your own module. Create mytools.py:
def add(a, b):
return a + b
def greet(name):
return "Hello " + nameThen use it in another file:
import mytools
print(mytools.add(5, 3))
print(mytools.greet("Aman"))Packages & pip
A package is a folder of modules. Many packages are not built in — you install them with pip, Python's package installer.
pip install numpy pip install pandas
After installing, import numpy and use it like any module.
Common Mistakes
- Naming your file the same as a real module (e.g.
random.py) — it confuses imports. - Forgetting to install a package with pip before importing.
- Expecting
randomoutput to be the same every run.
Practice Tasks
- Use
mathto find the area of a circle (pi r squared). - Use
randomto simulate rolling two dice and print the sum. - Make a module with two functions and import it into another file.
- Use the
statisticsmodule to find the mean of a list.
Summary
- A module is a reusable Python file; a package is a folder of modules.
- Import with
import,from ... import, orimport ... as. - Built-in: math, random, datetime, os, statistics.
- Install extra packages with
pip install.
