Module
What is a Module?
A module is a file containing Python code (functions, variables, classes) that you want to use in another program.
You can think of a module as a code library.
Get Sowmithra’s stories in your inbox
Join Medium for free to get updates from this writer.
Why use Modules?
- Code reuse
- Easy maintenance
- Better organization of large programs
Creating Your Own Module with Functions
File: Modules.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
Import the whole module
import Modules
print(Modules.add(5, 10))
print(Modules.sub(50, 10))Import specific functions
from Modules import div, add, sub
print(div(10, 5))
print(add(50, 25))
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(sub(a, b))Import all functions
from Modules import *
print(add(20, 25))
print(sub(5, 10))
print(mul(8, 10))
print(div(7, 10))Built-in Module: calendar
import calendar
m = int(input("Enter month number: "))
print(f"Month #{m} is: {calendar.month_name[m]}")Show a single month
import calendar
yy = 2023
mm = 4
print(calendar.month(yy, mm))Show a full year
import calendar
yy = 2017
print(calendar.calendar(yy))Built-in Module: datetime
| Code | Description | Example |
| ---- | -------------------- | -------- |
| `%A` | Full weekday name | Monday |
| `%a` | Short weekday name | Mon |
| `%B` | Full month name | December |
| `%b` | Short month name | Dec |
| `%d` | Day of month (01–31) | 09 |
| `%m` | Month (01–12) | 07 |
| `%Y` | Year (4 digits) | 2025 |
| `%y` | Year (2 digits) | 25 |
| `%H` | Hour (00–23) | 17 |
| `%I` | Hour (01–12) | 05 |
| `%p` | AM/PM | PM |Get Current Date and Time
import datetime
x = datetime.datetime.now()
print(x.year) # Current year
print(x.strftime("%A")) # Full weekday nameCustom Date
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B")) # Full month nameUser Input Date
import datetime
a = int(input("Enter the Year: "))
b = int(input("Enter the Month: "))
c = int(input("Enter the Day: "))
x = datetime.datetime(a, b, c)
print("Current Day:", x.strftime("%A"))




