What is a Python Module?

A module in Python is simply a file that contains Python code — like variables, functions, classes, or even runnable scripts.

A module is simply a .py file containing Python code that you can reuse in other programs.



Why Use Modules?

1. Code Reusability : Write once, use many times.

2. Organized Code : Split large programs into smaller, manageable files.

3. Built-in Help : Python has many useful built-in modules (like math, random, etc.).

4. Easy Collaboration : Teams can work on different modules.

5. Maintainability :When you need to fix a bug or add a new feature, you only have to work on the relevant module, not sift through thousands of lines of code.



How to Create a Module?

Any .py file is a module!



Example : calculator.py

def add(x, y):
    return x + y
def subtract(x, y):
    return x - y

You can use this module in another file :

import calculator
print(calculator.add(5, 3))  # Output: 8


Importing Modules :

Python provides multiple ways to import :


Syntax Description
import module_name Import whole module
import module_name as alias Import with an alias
from module import func Import specific function or class
from module import * Import everything (not recommended)


Built-in Modules (No Installation Needed) :


Module Use Case
math Advanced math functions
random Random number generation
datetime Work with dates and time
os Interact with operating system
sys System-specific functions


Python datetime Module :

The datetime module in Python is used to work with dates and times. It allows you to perform tasks like getting the current date, formatting time, adding/subtracting time, and much more.



Why Use datetime?

Python doesn’t handle date/time operations natively. The datetime module:



Importing datetime

import datetime


Getting Current Date & Time

from datetime import datetime

now = datetime.now()
print("Current date and time:", now)

#Output - Current date and time: 2025-07-16 16:45:23.456123


Useful Classes in datetime :


Class Description
date Deals with dates only
time Deals with time only
datetime Combines date and time
timedelta Represents time difference


Working with date

from datetime import date

today = date.today()
print("Today's date:", today)
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

#Output - 
Today's date: 2025-07-23
Year: 2025
Month: 7
Day: 23


Formatting Date and Time

from datetime import datetime

now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M:%S"))  # DD-MM-YYYY HH:MM:SS

#Output - 24-07-2025 03:02:58


Creating a Custom Date or Time

from datetime import datetime

dt = datetime(2024, 12, 25, 10, 30)
print("Custom datetime:", dt)

#Output - 
Custom datetime: 2024-12-25 10:30:00


Date Arithmetic with timedelta

from datetime import timedelta, date

today = date.today()
future = today + timedelta(days=10)
past = today - timedelta(days=5)

print("Today:", today)
print("10 days later:", future)
print("5 days ago:", past)

#Output - 
Today: 2025-07-24
10 days later: 2025-08-03
5 days ago: 2025-07-19


Parsing String to Date

from datetime import datetime

date_str = "16-07-2025"
date_obj = datetime.strptime(date_str, "%d-%m-%Y")
print("Parsed date:", date_obj)

#Output - 
Parsed date: 2025-07-16 00:00:00


Python math Module

The math module in Python provides access to mathematical functions and constants.

It's widely used for performing operations like square root, trigonometry, logarithms, rounding, etc.



How to Use math Module?

You need to import it first :

import math


Commonly Used Functions


Function Description Example
math.sqrt(x) Square root of x math.sqrt(16) → 4.0
math.pow(x, y) x raised to the power y (x^y) math.pow(2, 3) → 8.0
math.floor(x) Rounds down to nearest integer math.floor(3.7) → 3
math.ceil(x) Rounds up to nearest integer math.ceil(3.1) → 4
math.factorial(x) Factorial of x math.factorial(5) → 120
math.fabs(x) Absolute value (float) math.fabs(-5.2) → 5.2
math.log(x) Natural log (base e) math.log(10)
math.log10(x) Log base 10 math.log10(100) → 2
math.exp(x) Returns e^x math.exp(2)


Trigonometric Functions


Function Description
math.sin(x) Sine of x (x in radians)
math.cos(x) Cosine of x
math.tan(x) Tangent of x
math.radians(x) Converts degrees to radians
math.degrees(x) Converts radians to degrees


Example :

import math
angle = 90
radian = math.radians(angle)
print("sin(90°):", math.sin(radian))  # Output: 1.0


Math Constants


Constant Description Value
math.pi π (pi) 3.141592653589793
math.e Euler’s number (e) 2.718281828459045
math.tau 6.283185307179586
math.inf Infinity math.inf
math.nan Not a Number math.nan


Example Use Case :

import math
radius = 7
area = math.pi * math.pow(radius, 2)
print("Area of circle:", area)

#Output - 
Area of circle: 153.93804002589985


Rounding Functions


Function Description
round(x) Rounds to nearest integer
math.trunc(x) Rounds to nearest integer


Python Built-in Math Functions

Python provides several built-in mathematical functions (that don’t require importing the math module). These are helpful for basic arithmetic, rounding, and type conversion.


Let’s explore them with simple examples :



1. abs( ) – Absolute Value :

Returns the absolute (non-negative) value of a number.

print(abs(-7))      # Output: 7
print(abs(5.2))     # Output: 5.2


2. round( ) – Round to Nearest Integer :

Rounds a number to the nearest integer or to a specified number of decimal places.

print(round(3.6))        # Output: 4
print(round(3.14159, 2)) # Output: 3.14


3. max( ) – Maximum Value :

Returns the largest item in an iterable or among two or more values.

print(max(5, 9, 2))             # Output: 9
print(max([4, 8, 1, 6]))        # Output: 8


4. min( ) – Minimum Value :

Returns the smallest item in an iterable or among two or more values.

print(min(5, 9, 2))             # Output: 2
print(min([4, 8, 1, 6]))        # Output: 1


5. sum( ) – Total of All Items :

Returns the sum of all items in an iterable (like a list or tuple).

print(sum([1, 2, 3, 4]))        # Output: 10


6. pow( ) – Exponentiation :

Returns x raised to the power y (x^y). Same as x ** y.

print(pow(2, 3))     # Output: 8
print(pow(5, 2))     # Output: 25


7. divmod( ) – Division + Modulus :

Returns a tuple (quotient, remainder).

print(divmod(10, 3))   # Output: (3, 1)


8. bin( ), oct( ), hex( ) – Number Conversion :

Converts integers to binary, octal, or hexadecimal string representation.

print(bin(10))   # Output: '0b1010'
print(oct(10))   # Output: '0o12'
print(hex(10))   # Output: '0xa'


9. int( ), float( ) – Type Conversion :

Converts data types.

print(int(3.9))    # Output: 3
print(float(7))    # Output: 7.0


10. bool( ) – Convert to Boolean :

Returns True or False based on the value.

print(bool(0))      # Output: False
print(bool(5))      # Output: True


Practice Python Code Here: