Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Introduction to Modules

Python Modules Introduction - Complete Guide

Learn what modules are in Python, why they are important, and how to use them to organize your code.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is a Module?
  • Why Use Modules?
  • Types of Modules
  • Importing Modules
  • Common Built-in Modules
  • Module Search Path
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is a module — definition and purpose
  • Why use modules — benefits of using modules
  • Types of modules — built-in vs user-defined
  • Importing modules — different ways to import
  • Common built-in modules — useful modules to know
  • Module search path — how Python finds modules

What is a Module?

In Python, a module is simply a file containing Python code — definitions of functions, classes, and variables. It's a way to organize related code together, making it easier to manage and reuse.

Think of a module like a chapter in a book. Each chapter covers a specific topic, and together they form the complete book. Similarly, each module covers specific functionality, and together they form a complete program.

💡 Key concept: A module is a .py file that contains Python code. It's the fundamental building block of code organization in Python. By breaking code into modules, you make it more manageable, reusable, and maintainable.

Why Use Modules?

1

Benefits of Using Modules

# Without modules (everything in one file)
# main.py - 1000+ lines of code
# Hard to maintain, debug, and understand

# With modules (organized structure)
# project/
# ├── main.py           # Entry point
# ├── data_processing.py
# ├── calculations.py
# ├── validation.py
# └── utils.py

# Example: calculations.py
def add(a, b):
    """Add two numbers"""
    return a + b

def subtract(a, b):
    """Subtract two numbers"""
    return a - b

def multiply(a, b):
    """Multiply two numbers"""
    return a * b

def divide(a, b):
    """Divide two numbers"""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# Example: utils.py
def format_currency(amount):
    """Format a number as currency"""
    return f"${amount:,.2f}"

def validate_email(email):
    """Validate an email address"""
    return "@" in email and "." in email

# Example: main.py
import calculations
import utils

result = calculations.add(10, 5)
print(utils.format_currency(result))  # $15.00

# Benefits of modules:
# 1. Organization — related code grouped together
# 2. Reusability — modules can be used in multiple projects
# 3. Maintainability — easier to fix bugs and update
# 4. Testability — test each module independently
# 5. Collaboration — multiple developers can work on different modules
# 6. Namespace management — avoids name conflicts

Benefits of using modules:

  • Organization — group related code together
  • Reusability — use code in multiple projects
  • Maintainability — easier to update and debug
  • Testability — test each module independently
  • Collaboration — team members can work in parallel
  • Namespace management — avoid naming conflicts

Quick Check: What is the main benefit of using modules? (Answer: Code organization and reusability)

Types of Modules

2

Built-in vs User-Defined Modules

# Python has two main types of modules

# 1. Built-in Modules
# These come with Python and are always available
import sys
import os
import math
import datetime
import json
import random

# Example: Using the math module
import math
print(math.sqrt(16))    # 4.0
print(math.pi)          # 3.14159...
print(math.factorial(5)) # 120

# Example: Using the datetime module
import datetime
today = datetime.date.today()
print(today)            # 2026-08-02

# 2. User-Defined Modules
# These are modules you create yourself
# Save this as mymodule.py
# def greet(name):
#     return f"Hello, {name}!"
# 
# def add(a, b):
#     return a + b

# Then import it:
# import mymodule
# print(mymodule.greet("Alice"))  # Hello, Alice!

# 3. Third-Party Modules
# Modules created by the community, installed via pip
# import numpy
# import pandas
# import requests

# 4. Package vs Module
# Module: A single .py file
# Package: A directory containing multiple modules with __init__.py

Module types:

  • Built-in modules — come with Python (math, os, sys)
  • User-defined modules — created by you (.py files)
  • Third-party modules — installed via pip (numpy, pandas)
  • Package — a collection of modules in a directory

Quick Check: What is the difference between a module and a package? (Answer: A module is a .py file; a package is a directory containing modules)

Importing Modules

3

Different Ways to Import

# 1. Import the entire module
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.14159...

# 2. Import specific items
from math import sqrt, pi
print(sqrt(25))  # 5.0
print(pi)        # 3.14159...

# 3. Import with an alias
import datetime as dt
today = dt.date.today()
print(today)  # 2026-08-02

# 4. Import everything (not recommended)
from math import *
print(sin(0))    # 0.0
print(cos(0))    # 1.0

# 5. Import multiple modules
import os, sys, math
print(sys.version)

# 6. Import from a package
# from mypackage import module1
# from mypackage.module1 import function1

# 7. Dynamic import
import importlib
math = importlib.import_module('math')
print(math.sqrt(36))  # 6.0

# 8. Reload a module (if modified)
import importlib
import mymodule
importlib.reload(mymodule)

# 9. Check if module exists
try:
    import numpy
    print("NumPy is installed")
except ImportError:
    print("NumPy is not installed")

Import methods:

  • import module — full namespace
  • from module import item — specific items
  • import module as alias — alias
  • from module import * — avoid (pollutes namespace)
  • from package import module — from package

Quick Check: What is the recommended way to import modules? (Answer: Use 'import module' or 'from module import specific_function')

Common Built-in Modules

4

Useful Modules You Should Know

# 1. math - Mathematical functions
import math
print(math.sqrt(25))        # 5.0
print(math.factorial(5))    # 120
print(math.pi)              # 3.14159...
print(math.e)               # 2.71828...
print(math.sin(math.pi/2))  # 1.0

# 2. datetime - Date and time operations
import datetime
now = datetime.datetime.now()
print(now)                  # 2026-08-02 12:00:00
today = datetime.date.today()
print(today)                # 2026-08-02

# 3. os - Operating system interface
import os
print(os.getcwd())          # Current working directory
print(os.listdir('.'))      # List files in current directory

# 4. sys - System-specific parameters
import sys
print(sys.version)          # Python version
print(sys.platform)         # Operating system

# 5. json - JSON data handling
import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string)          # '{"name": "Alice", "age": 25}'
parsed = json.loads(json_string)
print(parsed)               # {'name': 'Alice', 'age': 25}

# 6. random - Generate random numbers
import random
print(random.randint(1, 10))    # Random integer between 1 and 10
print(random.random())          # Random float between 0 and 1
print(random.choice(['a', 'b', 'c']))  # Random choice

# 7. re - Regular expressions
import re
pattern = r'\d+'
text = "I have 3 apples and 5 oranges"
matches = re.findall(pattern, text)
print(matches)  # ['3', '5']

# 8. collections - Specialized data structures
from collections import Counter, defaultdict
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counter = Counter(words)
print(counter)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

Common built-in modules:

  • math — mathematical functions
  • datetime — date and time handling
  • os — operating system interface
  • sys — system-specific parameters
  • json — JSON data handling
  • random — random number generation
  • re — regular expressions
  • collections — specialized data structures

Quick Check: Which module would you use to work with JSON data? (Answer: json)

Module Search Path

5

How Python Finds Modules

# Python looks for modules in specific locations
# The search order is:

# 1. The current directory (where your script is)
# 2. PYTHONPATH environment variable
# 3. Installation-dependent default paths

import sys
print("Module search paths:")
for path in sys.path:
    print(f"  {path}")

# Adding to the search path
# Option 1: Appending to sys.path
sys.path.append('/my/custom/path')

# Option 2: Using PYTHONPATH environment variable
# export PYTHONPATH="/my/custom/path:$PYTHONPATH"

# Option 3: Using a .pth file
# Place a .pth file in the site-packages directory

# Checking if a module exists
try:
    import mymodule
    print("Module found!")
except ImportError:
    print("Module not found!")

# Getting module information
import math
print(dir(math))  # List all attributes in the module
print(help(math)) # Show module documentation

# Module file location
import math
print(math.__file__)  # Path to the module file

Module search path key points:

  • Current directory — first place Python looks
  • PYTHONPATH — environment variable for custom paths
  • Default paths — installed Python libraries
  • sys.path — list of all search paths
  • Can be modified — add custom paths if needed

Quick Check: What is the first place Python looks for a module? (Answer: The current directory)

Best Practices for Using Modules

6

Using Modules Effectively

# Best practices for working with modules

# 1. Import at the top of the file
# ✅ Good
import math
import os
import sys

def my_function():
    return math.sqrt(16)

# ❌ Bad - importing inside functions
def my_function():
    import math  # Import inside function
    return math.sqrt(16)

# 2. Use specific imports when possible
# ✅ Good - import only what you need
from math import sqrt, pi

# ❌ Bad - importing everything
from math import *

# 3. Use aliases for long module names
# ✅ Good
import datetime as dt

# ❌ Bad - typing datetime everywhere
import datetime

# 4. Group imports by type
# ✅ Good
import sys
import os
import json

from math import sqrt
from datetime import date

# 5. Avoid circular imports
# ❌ Bad - moduleA imports moduleB, moduleB imports moduleA

# 6. Use __all__ to control what gets imported with *
# In your module:
# __all__ = ['public_function1', 'public_function2']

# 7. Document your modules
"""
Module: mymodule.py
This module provides utility functions for data processing.

Functions:
    process_data(data) - Process data
    validate_data(data) - Validate data
"""

# 8. Use if __name__ == "__main__" for testing
def main():
    """Main function for testing"""
    print("Testing module...")

if __name__ == "__main__":
    main()

# 9. Keep modules focused
# Each module should have a single responsibility

Module best practices:

  • Import at top — keep imports at the beginning of files
  • Specific imports — import only what you need
  • Use aliases — for long or commonly used module names
  • Group imports — organize imports logically
  • Avoid circular imports — can cause import errors
  • Document modules — add docstrings to explain purpose
  • Use __name__ == "__main__" — for testing module

Quick Check: Where should you place import statements? (Answer: At the top of the file)

Try It Yourself

Experiment with modules in the editor below. Try importing different modules and using their functions.

Loading Pyodide... 0%
Python Code Editor
========================================
MODULES INTRODUCTION PRACTICE
========================================

1. IMPORTING AND USING MODULES
Square root of 25: 5.0
Pi: 3.141592653589793
Today: 2026-08-02
Random number between 1-10: 7

2. SPECIFIC IMPORTS
5! = 120
Euler's number: 2.718281828459045
Current time: 12:00:00.123456

3. IMPORT WITH ALIAS
JSON string: {"name": "Alice", "age": 25}

4. USING THE OS MODULE
Current working directory: /home/user
Files in current directory: 42 files

5. USING THE SYS MODULE
Python version: 3.10.0
Platform: linux

Modules introduction practice complete!
🏆

You've Got It!

You now understand what Python modules are, why they are important, and how to use them. This is the foundation for working with the Python ecosystem!

Quick Quiz

Test what you've learned:

1. What is a module in Python?
2. What is the difference between a module and a package?
3. What does the following import do: from math import sqrt
4. Which module would you use to work with JSON data?
5. Where does Python look for modules first?

Frequently Asked Questions

What is the difference between a module and a package? ▼

A module is a single .py file containing Python code. A package is a directory that contains multiple modules and a special __init__.py file. Packages help organize modules in a hierarchy.

Why should I use modules? ▼

Modules make your code organized, reusable, maintainable, and easier to test. They help you follow the DRY principle and allow multiple developers to work on different parts of a project simultaneously.

What is the PYTHONPATH environment variable? ▼

PYTHONPATH is an environment variable that tells Python where to look for modules. It's a list of directories that Python searches in addition to the default search paths.

What's a common interview question about modules? ▼

Common questions include: "What is the difference between a module and a package?" "What is the purpose of __init__.py?" and "Explain different ways to import modules."

Can I create my own modules? ▼

Yes! Any Python file you create can be imported as a module. Just save it as a .py file and use import filename in another script (without the .py extension).

What is the purpose of if __name__ == "__main__"? ▼

if __name__ == "__main__" is used to run code only when the module is executed directly, not when it's imported. It's commonly used for testing modules and for creating executable scripts.

Where to Go From Here

Now that you understand the basics of modules, check out these related topics:

Inbuilt Modules

Explore Python's most useful built-in modules in detail.

Learn More →

User-Defined Modules

Learn how to create and use your own modules.

Learn More →

📝 Assignments

Practice what you've learned with assignments.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Lambda Functions Next: Inbuilt Modules in Python →