HomeComputer ScienceClass 11Introduction to Python Modules

Chapter 9: Introduction to Python Modules

1. Introduction

When your program grows big, writing everything in a single file becomes messy. Modules help you organize code into separate files — neat, reusable, and easy to manage.

Think of a module as a toolbox: you open it and use only the tools you need.

Example: greet.py Module

# greet.py - A simple greeting module
def say_hello(name):
    return f"Hello, {name}!"

def say_goodbye(name):
    return f"Goodbye, {name}!"

# Usage in main program:
# import greet
# print(greet.say_hello("Alice"))

2. Library or Package

A library is a collection of ready-made code — functions, classes, and modules that you can use directly in your program.

Key idea: A library is like a full bookshelf of helpful books.

Examples of Python Libraries:

  • NumPy - for numerical calculations
  • Pandas - for handling data
  • Matplotlib - for drawing graphs
import math        # math is a standard library
print(math.sqrt(25))

Package in Python:

A package is a collection of related modules stored together in a directory. It must contain a special file named __init__.py (even if empty).

import numpy as np  # importing the numpy package
print(np.array([1,2,3]))

Library vs Package Comparison

FeatureLibraryPackage
DefinitionCollection of modules, functions, and classesDirectory containing related modules
StructureCan be single or multiple modulesMust have __init__.py file
Examplemath, randomnumpy, pandas
Useimport mathimport numpy as np

Key Points:

  • Module - Single Book (one Python file with code)
  • Package - Bookshelf Section (folder with many related books)
  • Library - Full Library Building (huge collection of many bookshelves and books)

3. Modules in Python

A module is just a Python file (.py) containing variables, functions, or classes. Python already has hundreds of modules built-in — you do not need to write everything yourself!

Module Contents

ObjectDescription
1. DocstringA short text at the top explaining what the module does. Written in triple quotes (""" ... """).
2. Variables and ConstantsValues stored inside the module. Constants are in CAPITALS by convention.
3. ClassesBlueprints for creating objects. Group related data and functions together.
4. ObjectsActual instances created from classes inside the module.
5. StatementsRegular Python instructions that run when the module is imported.
6. FunctionsBlocks of reusable code that perform specific tasks.

Advantages of Python Modules

1. Code Reusability

Write code once and use it in many programs.

2. Better Organization

Split code into modules for neat management.

3. Easy Maintenance

Fix bugs in one place, works everywhere.

4. Avoids Code Duplication

Import common functions instead of rewriting.

5. Namespace Management

Each module has its own namespace.

6. Faster Development

Use pre-built modules to focus on problem-solving.

7. Team Collaboration

Different team members can work on different modules.

4. Module Name in Python

In Python, a module name is simply the name of the file without the .py extension.

Example 1 - Built-in module

import math
print(math.sqrt(25))

Module name: math (built-in module)

Example 2 - User-defined module

# Inside mytools.py
def greet():
    print("Hello from mytools module!")
# To use it in another program:
import mytools
mytools.greet()

Module name: mytools (filename without .py)

Rules for Module Names

  • • Use letters, numbers, and underscore (_) only
  • • Do not start with a number
  • • No spaces or special characters
  • • Keep names lowercase (easier to read)
  • • Do not use Python keywords like for, while, if
  • • Do not use names of built-in modules like math, os

Quick Tip

Filename → Module name → Import name
hello.py → module name is hello → import using import hello

5. Importing Python Modules

To use a module, it must be imported into the main program or another module. Any Python file can be used as a module by importing it.

1. Basic Import (Most Common)

import module_name
# Gives access to all variables, constants, and functions in the module
import math
print(math.sqrt(16))  # Using dot notation

Note: The import statement does not give direct access to functions. Use dot notation: module_name.function_name()

2. Import Multiple Modules

import module1, module2, module3

3. From Import (Specific Functions)

from <module_name> import <function_name(s)>
# Or
from <module_name> import function1, function2, function3
from math import sqrt
print(sqrt(16))  # No need for math. prefix

4. Import All (Not Recommended)

from <module_name> import *
# Imports all names from module into current namespace

5. Member Aliasing

You can rename modules or functions while importing:

import math as m
print(m.pi)

from math import sqrt as s
print(s(25))

Retrieving Objects from Modules

dir() function - Lists all names (objects) inside a module.

import area
dir(area)
# Output: Shows built-in attributes (__doc__, __name__, etc.)
# Also lists user-defined functions like circle_area, square_area, etc.

Key Point: Use dir(module_name) to get complete information about what is inside the module.

6. Locating Modules

Python looks for modules in a certain search path:

  1. Current folder
  2. Installed packages folder
  3. System path for Python libraries

If Python cannot find a module, you will see an ImportError.

7. Standard Built-in Python Modules

Python comes with many ready-made modules for common tasks:

Math Module

import math
print(math.sqrt(25))      # 5.0
print(math.pow(2, 3))     # 8.0
print(math.factorial(5))  # 120
print(math.pi)            # 3.14159...
print(math.ceil(4.3))     # 5
print(math.floor(4.7))    # 4

Random Module

import random
print(random.random())        # 0.0 to 1.0
print(random.randint(1, 10))  # 1 to 10
print(random.choice([1,2,3])) # Random choice
random.shuffle([1,2,3,4])     # Shuffle list

DateTime Module

import datetime
now = datetime.datetime.now()
print(now)                    # Current date/time
print(now.year)               # Current year
print(now.strftime("%Y-%m-%d")) # Format date

OS Module

import os
print(os.getcwd())           # Current directory
os.chdir('/path/to/dir')     # Change directory
print(os.listdir('.'))       # List contents
os.mkdir('new_folder')       # Create directory
print(os.path.exists('file.txt'))  # Check file

Sys Module

import sys
print(sys.version)           # Python version
print(sys.path)              # Module search path
sys.exit()                   # Exit program

Built-in Functions (No Import Needed)

Some functions are already available everywhere — you do not need to import any module:

print()len()type()max()min()round()abs()sum()

8. User-Defined Modules Example

You can create your own modules:

Step 1: Create mytools.py

# save this as mytools.py
def greet():
    print("Hello from mytools!")

def calculate_area(length, width):
    return length * width

PI = 3.14159

Step 2: Use in main program

# main program
import mytools

mytools.greet()
area = mytools.calculate_area(5, 3)
print(f"Area: {area}")
print(f"PI value: {mytools.PI}")

Key Points to Remember

  • • Modules help organize and reuse code effectively
  • • Python has many built-in modules for common tasks
  • • You can create custom modules by saving code in .py files
  • • Use import statements to access module functions
  • • Always document your modules with docstrings
  • • Follow naming conventions and best practices
  • • Use dir() to explore module contents
  • • Libraries contain collections of related modules

Important Terms

TermMeaning
__name__Tells whether the file is run directly (__main__) or imported (module name)
__main__Value of __name__ when the file is executed directly
Module name rulesUse letters, numbers, underscore; avoid spaces, digits at start, special chars

Related Resources

Need Help?

Join our tuition classes for personalized guidance and doubt clearing.

Register for Classes →