- Home
- /
- Python Modules
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Modules
Python Recursion
In Python, a module is simply a file that contains Python code. You can think of it like a toolbox — instead of rewriting code again and again, you can just grab what you need from a module. This keeps your programs clean, organized, and reusable.
Built-in Modules
Python comes with many ready-made modules. You can use them by simply importing them. A few common ones include:
math, random, datetime, statistics, json, turtle, csv
Example: Using the math module
import math
angle = math.pi / 4 # 45 degrees in radians
print("Sine of 0 is", math.sin(0))
print("Sine of 45 degrees is", math.sin(angle))
Output:
Sine of 0 is 0.0
Sine of 45 degrees is 0.7071067811865475
Creating and Using Your Own Module
You can make your own module by writing Python functions in a .py
file. Suppose we create a file named calculator.py
:
# calculator.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
Now let’s use this module in another file:
# app.py
import calculator
print("Sum:", calculator.add(10, 5))
print("Difference:", calculator.subtract(10, 5))
Output:
Sum: 15
Difference: 5
Import With Alias
Sometimes module names can be long. You can shorten them using an alias:
import math as m
print("Square root of 81 is", m.sqrt(81))
Output:
Square root of 81 is 9.0
Import Specific Functions
You don’t always have to import the whole module. You can pick only what you need:
from calculator import add, multiply
print(add(3, 4))
print(multiply(3, 4))
If you try to use something that wasn’t imported:
print(divide(10, 2)) # This will give an error
You’ll get:
NameError: name 'divide' is not defined
Import Everything From a Module
If you want to use everything from a module without prefixing it with the module name:
from calculator import *
print(add(6, 3))
print(subtract(6, 3))
The dir() Function
The dir()
function lets you see what functions and variables are available in a module.
import math
print(dir(math))
This will print a long list of available features in the math
module.
Summary
A module is just a Python file you can reuse.
Use
import
to access built-in or custom modules.Use
as
to shorten long module names.Use
from module import function
to import specific parts.Use
dir()
to explore what’s inside a module.