Next

Built-in Modules

  • Understand how to use Python’s built-in modules like math, random, and datetime to simplify development and improve efficiency.

  • Built-in Python Modules

    math, random, datetime

    1. math Module

    What is the math Module?

    The math module provides mathematical functions and constants used for:

    • Calculations

    • Trigonometry

    • Power & square root

    • Rounding operations

    Used in scientific, financial, and engineering applications.

    Importing math Module

    import math

    Common math Functions

    Function

    Description

    math.sqrt(x)

    Square root

    math.pow(x, y)

    Power

    math.ceil(x)

    Round up

    math.floor(x)

    Round down

    math.factorial(x)

    Factorial

    math.pi

    Value of π

Square Root Using math

Calculates square root of a number.

import math

print(math.sqrt(25))

Rounding Numbers

Demonstrates ceil and floor functions.

import math

print(math.ceil(4.2))
print(math.floor(4.8))

Using Mathematical Constants

Uses value of pi.

import math

print(math.pi)
  • 2 random Module

    What is the random Module?

    The random module is used to generate random numbers or values.

    Used in:

    • Games

    • Simulations

    • OTP generation

    • Random selections

    Importing random Module

    import random

    Common random Functions

    Function

    Description

    random.random()

    Float (0 to 1)

    random.randint(a, b)

    Integer between a & b

    random.choice(seq)

    Random element

    random.shuffle(list)

    Shuffle list


Random Integer

Generates a random number between 1 and 10.

import random

print(random.randint(1, 10))

Random Choice

Selects a random item from a list.

import random

colors = ["red", "blue", "green"]
print(random.choice(colors))
  • 3. datetime Module

    What is the datetime Module?

    The datetime module is used to work with dates and times.

    Used in:

    • Attendance systems

    • Billing systems

    • Logs and reports

    • Time-based applications

    Importing datetime Module

    import datetime

  • Getting Current Date & Time

Current Date and Time

Displays current system date and time.

import datetime

now = datetime.datetime.now()
print(now)
  • Getting Only Date or Time

Current Date

Displays current date only.

import datetime

today = datetime.date.today()
print(today)

Current Time

Displays current time only.

import datetime

time = datetime.datetime.now().time()
print(time)
  • Formatting Date & Time (strftime)

Formatting Date

Formats date into readable format.

import datetime

now = datetime.datetime.now()
print(now.strftime("%d-%m-%Y %H:%M:%S"))
  • Creating Custom Date

Creating a Custom Date

Creates a specific date.

import datetime

d = datetime.date(2025, 1, 1)
print(d)
  • Summary Table

    Module

    Purpose

    math

    Mathematical operations

    random

    Random values

    datetime

    Date & time handling

Next