Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Built-in Modules in Python

Learn about useful modules that are already available with Python and can be imported directly into your program.

What are Built-in Modules?

Python comes with many useful modules that are available as part of the standard library.

These modules provide ready-to-use functionality for common programming tasks such as mathematics, dates, random numbers, file paths and JSON data.

Simple Definition: Built-in or standard-library modules are modules provided with Python that we can import and use without writing the functionality ourselves.

Why Do We Use Built-in Modules?

  • Save development time.
  • Reuse ready-made functionality.
  • Avoid writing common logic from scratch.
  • Make programs shorter and easier to maintain.
  • Solve common programming problems quickly.

Built-in Modules Diagram

Different built-in modules help us perform different types of tasks.

Python Standard Library

Ready-to-use modules

↓
math

Mathematical operations

random

Random values

datetime

Date and time

os

Operating-system features

json

JSON data

re

Regular expressions

↓
Python Application

Use the required module for the required task.

1. math Module

The math module provides mathematical functions and constants.

Example

import math

print(math.sqrt(25))
print(math.pow(2, 3))
print(math.pi)

Output:

5.0
8.0
3.141592653589793

Common math Functions

Function Purpose
sqrt() Returns square root.
pow() Returns a number raised to a power.
ceil() Rounds a number upward.
floor() Rounds a number downward.
pi Provides the value of pi.
import math

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

Output:

5
4

2. random Module

The random module is used to generate pseudo-random values and make random selections.

Random Number

import random

number = random.randint(1, 10)

print(number)

The program generates an integer between 1 and 10.

Random Choice

import random

courses = ["Python", "Java", ".NET", "MERN"]

course = random.choice(courses)

print(course)

One item is selected randomly from the list.

Common random Functions

  • randint() - returns a random integer within the given range.
  • choice() - selects one item from a sequence.
  • random() - returns a floating-point value between 0 and 1.

3. datetime Module

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

Current Date and Time

from datetime import datetime

current_time = datetime.now()

print(current_time)

This returns the current date and time.

Current Date

from datetime import date

today = date.today()

print(today)

Output will contain the current date.

4. os Module

The os module provides functions for interacting with the operating system.

Current Directory

import os

print(os.getcwd())

os.getcwd() returns the current working directory.

List Files and Folders

import os

files = os.listdir()

print(files)

os.listdir() returns names of files and folders in the specified directory.

Check Path

import os

print(os.path.exists("example.txt"))

This checks whether the given path exists.

5. json Module

The json module is used to work with JSON data.

Python Dictionary to JSON

import json

student = {
    "name": "Rahul",
    "age": 22
}

json_data = json.dumps(student)

print(json_data)

Output:

{"name": "Rahul", "age": 22}

JSON to Python Object

import json

json_data = '{"name": "Rahul", "age": 22}'

student = json.loads(json_data)

print(student["name"])
print(student["age"])

Output:

Rahul
22

6. re Module

The re module is used for working with regular expressions and searching for text patterns.

import re

text = "My phone number is 9876543210"

result = re.search(r"\d{10}", text)

if result:
    print(result.group())

Output:

9876543210

The regular expression \d{10} searches for a sequence of 10 digits.

Some Other Useful Standard Modules

sys

Provides access to Python runtime and system-related information.

collections

Provides specialized container data types.

statistics

Provides common statistical functions.

pathlib

Provides an object-oriented way to work with file system paths.

time

Provides functions for working with time-related operations.

calendar

Provides functions related to calendars and dates.

Different Ways to Import Built-in Modules

Import Complete Module

import math

print(math.sqrt(49))

Import Specific Function

from math import sqrt

print(sqrt(49))

Import with Alias

import datetime as dt

print(dt.date.today())

Common Built-in Modules Comparison

Module Main Use Example
math Mathematical calculations math.sqrt()
random Random values random.randint()
datetime Date and time datetime.now()
os Operating-system tasks os.getcwd()
json JSON data json.dumps()
re Pattern matching re.search()

Example 🔓🤓

The following program uses multiple built-in modules together.

import math
import random
from datetime import date

number = random.randint(1, 100)

print("Random Number:", number)

print("Square Root:", math.sqrt(number))

print("Today:", date.today())

This example shows how different standard-library modules can solve different tasks in the same program.

Common Mistakes

  • Writing the wrong module name.
  • Forgetting to import the module.
  • Using a function without the correct module prefix.
  • Importing a specific function and then trying to use it with the module prefix.

Practice Programs

  1. Use the math module to calculate square root and power.
  2. Use random to generate a random number between 1 and 100.
  3. Display the current date using datetime.
  4. Use os to display the current working directory.
  5. Convert a Python dictionary into JSON using json.
  6. Use re to search for a phone number in a string.

Summary

Python provides many useful standard-library modules for common programming tasks. The math module is used for mathematical operations, random for random values, datetime for dates and times, os for operating-system operations, json for JSON data and re for regular expressions. These modules can be imported and reused directly in Python programs.