Python Modules

Python Modules are essential for organizing and reusing code in Python programming. This article explains what modules are, how to create and use them, and their types. We will also explore their benefits and practical uses to give you a clear understanding of Python modules.

Contents:

  1. What is Python Module?
  2. Types of Modules in Python
  3. Creating a Module in Python
  4. Built-in Modules in Python
  5. User-Defined Modules in Python
  6. Third-Party Modules in Python
  7. Popular Built-in Modules in Python
  8. Best Practices for Using Modules
  9. FAQs on Python Modules

What is Python Module?

A Python module is a file with Python code that contains functions, classes, and variables for reuse. It helps organize code and supports modular programming. You can import modules using the import statement, and they can be built-in or user-defined.

Types of Modules in Python

Python modules fall into three main categories:

  • Built-in Modules – These are pre-installed modules that come with Python. You can use them without any installation.
  • User-Defined Modules – These are custom modules created by developers to organize their own code into reusable files.
  • Third-Party Modules – Created by other developers and are available through the Python Package Index (PyPI).

advertisement

Creating a Module in Python

Creating a module in Python is straightforward. A module is simply a Python file (.py) that contains functions, classes, and variables that can be reused in other Python programs.

Steps to Create a Module:

1. Create a Python File

Create a new file and name it something meaningful, such as sanfoundry.py. This file will contain the functions and classes you want to use in other programs.

⚡ Claim Your Free Java Certification - December 2025

Example (sanfoundry.py):

# sanfoundry.py
def quiz(name):
    return f"Welcome to {name}'s Quiz!"
 
def score(a, b):
    return f"Your total score is: {a + b}"
 
subject = "Python Programming"

2. Importing and Using the Module

Create another file named main.py and import sanfoundry:

# main.py
import sanfoundry
 
print(sanfoundry.quiz("Accenture"))       # Output: Welcome to Accenture Quiz!
print(sanfoundry.score(45, 50))       # Output: Your total score is: 95
print(sanfoundry.subject)             # Output: Python Programming

3. Importing Specific Functions/Variables

advertisement
from sanfoundry import quiz, subject
 
print(quiz("TCS"))     # Output: Welcome to TCS Quiz!
print(subject)         # Output: Python Programming

4. Renaming Module Using as

import sanfoundry as sf
 
print(sf.quiz("IBM"))     # Output: Welcome to IBM Quiz!
print(sf.score(40, 35))    # Output: Your total score is: 75

Built-in Modules in Python

Built-in modules come pre-installed in Python and offer useful functions without needing extra installation.

Importing Built-in Modules

Use import to load built-in modules.

import math
import random
import datetime

Common Built-in Modules in Python

1. math Module

The math module provides mathematical functions like square root, trigonometry, logarithms, etc.

import math
 
angle = 45
print("Sine of 45:", math.sin(math.radians(angle)))  # Output: 0.7071
print("Square Root of 64:", math.sqrt(64))          # Output: 8.0

2. random Module

The random module is used to generate random numbers.

import random
 
# Random score between 0 and 100
print("Random Quiz Score:", random.randint(0, 100))  
subjects = ["Python", "Java", "DBMS"]
print("Random Subject:", random.choice(subjects))
# Output: Random subject

3. datetime Module

The datetime module helps in handling date and time operations.

import datetime
 
now = datetime.datetime.now()
print("Current Date and Time:", now) # Output: Current date and time
print("Year:", now.year) # Output: Current year

4. os Module

The os module provides functions to interact with the operating system, such as reading environment variables, creating directories, etc.

import os
 
print(os.name)  # Output: 'nt' for Windows, 'posix' for Linux/macOS
print(os.getcwd())  # Get current working directory
os.mkdir("test_folder")  # Create a new directory

5. sys module

The sys module provides system-related functionalities.

import sys
 
print(sys.version)  # Output: Python version
print(sys.platform)  # Output: OS platform
sys.exit()  # Exit the program

6. json Module

The json module allows encoding and decoding of JSON data.

import json
 
data = {"name": "Sanfoundry", "quiz": "Python"}
json_data = json.dumps(data)
print("JSON Data:", json_data)
 
# Output: JSON Data: {"name": "Sanfoundry", "quiz": "Python"}

7. urllib Module

urllib Module handles URL operations.

import urllib.request
 
url = "https://www.sanfoundry.com/"
print("Accessing URL:", url)
response = urllib.request.urlopen(url)
print("Response Code:", response.getcode())

User-Defined Modules in Python

A user-defined module is a Python file created by the user that contains custom functions, classes, or variables that can be imported and used in other programs.

Creating a User-Defined Module

To create a module, make a .py file and define functions, classes, or variables inside it.

Folder Structure:

/project
├── main.py
└── sanfoundry.py
# sanfoundry.py
 
def quiz(name):
    """Returns a welcome message for the quiz."""
    return f"Welcome to {name}'s Quiz!"
 
def score(marks):
    """Returns the quiz score."""
    return f"Your total score is: {marks}"
 
subject = "Python Programming"

Importing and Using a User-Defined Module

You can import and use a user-defined module in another Python file.

# main.py
import sanfoundry
 
print(sanfoundry.quiz("Python"))    # Output: Welcome to Python's Quiz!
print(sanfoundry.score(95))        # Output: Your total score is: 95
print(sanfoundry.subject)          # Output: Python Programming

Using dir() to List Module Contents

import sanfoundry
 
print(dir(sanfoundry))  # Lists available functions and variables

Checking Module Location

import sanfoundry
 
print(sanfoundry.__file__)  # Displays the file path of the module

Reloading a Module

To reload a module after making changes:

import importlib
import sanfoundry
 
# Reload module
importlib.reload(sanfoundry)

Using __name__ == “__main__” in a Module

# sanfoundry.py
def greet():
    print("Welcome to Sanfoundry Quiz!")
 
if __name__ == "__main__":
    greet()

If sanfoundry.py is run directly, it will execute greet(). If imported, this block won’t run.

Third-Party Modules in Python

Third-party modules are Python packages or libraries developed by the community that extend the functionality of Python. These modules are not included in the standard library and need to be installed separately using package managers like pip.

1. Installing Third-Party Modules

Use pip (Python Package Installer) to install third-party modules.

# Syntax to install a package
pip install package_name

2. Popular Third-Party Modules

(i) numpy – Numerical Computation

pip install numpy
import numpy as np
 
arr = np.array([1, 2, 3, 4, 5])
print("Array Elements:", arr)
print("Sum of Elements:", np.sum(arr))

Output:

Array Elements: [1 2 3 4 5]
Sum of Elements: 15

(ii) pandas – Data Analysis and Manipulation

pip install pandas
import pandas as pd
 
data = {'Subject': ['Python', 'Java', 'DBMS'], 'Score': [90, 85, 88]}
df = pd.DataFrame(data)
print("Quiz Data:\n", df)

Output:

Quiz Data:
  Subject  Score
0  Python     90
1    Java     85
2    DBMS     88

(iii) matplotlib – Data Visualization

pip install matplotlib
import matplotlib.pyplot as plt
 
subjects = ["Python", "Java", "DBMS"]
scores = [90, 85, 88]
 
plt.bar(subjects, scores)
plt.title("Quiz Scores")
plt.show()

(iv) flask – Web Application Framework

pip install flask
from flask import Flask
 
app = Flask(__name__)
 
@app.route("/")
def home():
    return "Welcome to the Sanfoundry Flask App!"
 
if __name__ == "__main__":
    app.run()

(v) requests – Handling HTTP Requests

pip install requests
import requests
 
response = requests.get("https://www.sanfoundry.com/")
print("Status Code:", response.status_code) # Output: Status Code: 200

3. Checking Installed Packages

pip list

4. Uninstalling a Package

pip uninstall package_name

Popular Built-in Modules in Python

Here are some commonly used Built-in modules:

Module Name Purpose Example
math Mathematical operations import math
random Generate random numbers import random
datetime Work with dates and times import datetime
time Time-related functions import time
sys System-specific parameters & functions import sys
os Interact with the operating system import os
shutil File operations (copy, move, delete) import shutil
platform Get system information import platform
re Regular expressions import re
json JSON parsing import json
csv Read and write CSV files import csv
threading Multi-threading import threading
multiprocessing Multi-processing import multiprocessing
urllib URL handling import urllib.request
collections Specialized data structures import collections
itertools Iterator utilities import itertools

Best Practices for Using Modules

Use meaningful names for modules.

  • Keep modules small and focused on a single purpose.
  • Use __all__ to define public functions in a module when using from module import *.
  • Avoid circular imports (where two modules import each other).
  • Use virtual environments to manage dependencies (venv, pipenv, conda).
  • Import Only What You Need – Avoid unnecessary imports for better performance.

FAQs on Python Modules

1. What is a Python module?
A module is a file containing Python code, such as functions and variables, that can be imported and reused in other programs.

2. How is a module different from a package?
A module is a single .py file, whereas a package is a collection of modules organized in a directory with an __init__.py file.

3. How do you import a module in Python?
Modules can be imported using the import statement, allowing access to their functions and classes.

4. What are built-in modules?
These are standard Python modules that come pre-installed, such as math, sys, os, and random.

5. What are third-party modules?
These are external modules installed using package managers like pip, such as numpy, pandas, and requests.

6. What are user-defined modules?
These are custom modules created by users to organize reusable code into separate files.

7. What is the purpose of if __name__ == “__main__”?
It ensures that certain code runs only when the script is executed directly, not when imported as a module.

8. What is a virtual environment, and why is it important?
A virtual environment isolates project dependencies, preventing conflicts between different projects. It is managed using tools like venv or conda.

Key Points to Remember

Here is the list of key points we need to remember about “Python Modules”.

  • A Python module is just a .py file with reusable functions, classes, or variables that can be imported into other programs.
  • There are three types of modules: built-in (like math and random), user-defined (your own Python files), and third-party (pip-installed packages like numpy and pandas).
  • Creating a module is easy—write a .py file, define functions or variables, and import it wherever needed.
  • Importing can be done in different ways: import module_name, from module_name import function_name, or import module_name as alias.
  • Useful built-in modules include math (math operations), random (random numbers), datetime (date/time handling), os (OS interactions), and sys (system-related operations).
  • Third-party modules like numpy, pandas, matplotlib, requests, and flask extend Python’s capabilities and can be installed using pip install package_name.
  • Use dir(module_name) to list functions/variables inside a module and module_name.__file__ to check its location.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.