PYTHON Tutorial

Modules and Packages

Introduction

Modules and packages are organizational units in Python code. Modules are individual Python files containing code that can be imported into other Python programs, while packages are collections of related modules.

Practical Steps:

Creating a Module:

Create a new Python file (.py) and define functions, classes, or variables in it. Save it as your_module.py.

Using a Module:

In another Python program, use the import statement to import the module:

import your_module

You can then access the module's contents using the module name, e.g.:

your_module.function()
Creating a Package:

Create a new directory and place your related modules within it. Create an __init__.py file in the directory to indicate that it is a package.

Using a Package:

Use the import statement to import the package:

import your_package

You can then access modules within the package using the package name, e.g.:

your_package.your_module.function()

Key Concepts:

  • Python import: Used to import modules or packages into a program.
  • Python standard library: A collection of built-in modules that come with Python.
  • Python custom modules: Modules created by programmers for specific purposes.

Example:

Creating the Module math_utils.py:

def add_numbers(a, b):
    return a + b

Using the Module in Another Program:

import math_utils

result = math_utils.add_numbers(3, 5)
print(result)  # Output: 8

This example demonstrates how to create and use a module to perform simple mathematical operations.