0% found this document useful (0 votes)
22 views6 pages

Understanding Python Modules Explained

A module in Python is a .py file containing code such as functions, classes, or variables that can be reused across different programs. Modules enhance code organization, readability, reusability, and maintainability, while also managing namespaces to prevent naming conflicts. Python has built-in modules and allows users to create their own, which can be imported in various ways to utilize their functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views6 pages

Understanding Python Modules Explained

A module in Python is a .py file containing code such as functions, classes, or variables that can be reused across different programs. Modules enhance code organization, readability, reusability, and maintainability, while also managing namespaces to prevent naming conflicts. Python has built-in modules and allows users to create their own, which can be imported in various ways to utilize their functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is a Module in Python?

Definition:

 A module in Python is a file containing Python code—this can include functions,


classes, or variables.
 Modules allow you to organize code logically and reuse it across multiple programs.
 You can import a module in another Python program to use its content.

Key Points:

 Any file with .py extension is a module.


 Python has many built-in modules like math, random, os, datetime.
 You can also create your own modules for custom tasks.

Example of a User-defined Module

Step 1: Create a module


Create a file called [Link]:

# [Link]

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Cannot divide by zero"

Step 2: Use this module in another Python program


Create another file called [Link]:

# [Link]
import calculator # importing the module

print("Addition:", [Link](10, 5)) # 15


print("Subtraction:", [Link](10, 5))# 5
print("Multiplication:", [Link](4, 3)) # 12
print("Division:", [Link](10, 2)) # 5.0

Output:
Addition: 15
Subtraction: 5
Multiplication: 12
Division: 5.0

Need for Modules in Python:


The use of modules in Python addresses several crucial needs in software development:

 Code Organization and Readability:

Modules allow for the logical grouping of related code into distinct files. This structure makes
large projects more manageable, improves code readability, and helps in understanding the
purpose of different parts of a program.

 Code Reusability:

Modules promote code reusability by allowing you to define functions, classes, or variables
once and then import and use them across multiple different Python scripts or projects. This
eliminates the need to rewrite the same code, saving development time and reducing potential
errors.

 Namespace Management:

Each module has its own independent namespace. This prevents naming conflicts when
integrating code from different sources, as variables or functions with the same name in
different modules will not clash. When you import a module, its contents are accessed through
its namespace (e.g., module_name.function_name).

 Maintainability and Scalability:

By breaking down a large application into smaller, self-contained modules, maintenance


becomes easier. Changes or updates to a specific functionality can be isolated to its respective
module without affecting other parts of the program. This also enhances the scalability of
applications, as new features can be added as new modules or by extending existing ones.

 Collaboration:
Modules facilitate team collaboration by allowing multiple developers to work on different
parts of a project concurrently, each focusing on their specific modules without interfering
with others' work.
Creating a Module
Definition:

 A module is simply a Python file (.py) containing functions, classes, or variables.


 You can reuse this module in multiple programs by importing it.

Steps to create a module:

1. Open a text editor or IDE.


2. Write some Python functions, classes, or variables.
3. Save the file with a .py extension (this file becomes a module).

Example – Creating a Module ([Link])

# [Link]

# Function to add two numbers


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

# Function to subtract two numbers


def subtract(a, b):
return a - b

# Function to multiply two numbers


def multiply(a, b):
return a * b

# Function to divide two numbers


def divide(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero"

This file [Link] is now a Python module.

2. Importing a Module
Definition:

 Importing a module means bringing its functions, classes, or variables into another
Python program so you can use them.

Ways to Import a Module:

2.1 Import the Entire Module


import calculator

print([Link](5, 3)) # 8
print([Link](4, 2)) # 8

 Use module_name.function_name() to access functions.

2.2 Import Specific Functions


from calculator import add, divide

print(add(10, 7)) # 17
print(divide(15, 3)) # 5.0

 Only the imported functions are available directly.

2.3 Import with Alias


import calculator as calc

print([Link](10, 3)) # 7
print([Link](2, 5)) # 10

 Useful to shorten module name or avoid conflicts.

2.4 Import All Functions (Not Recommended)


from calculator import *

print(add(5, 6)) # 11
print(subtract(10, 3)) # 7

 Avoid in large programs to prevent name conflicts.

What is Path Searching of a Module?


 When you import a module, Python needs to know where to find it.
 Python searches for the module in a specific sequence of locations, called the module
search path.
 This ensures Python can locate both built-in and user-defined modules.

Module Search Order


When you do import module_name, Python searches in the following order:

1. Current directory – The directory where the running script is located.


2. Directories in PYTHONPATH environment variable – These are user-defined
directories where Python looks for modules.
3. Standard library directories – Built-in Python modules (like math, os, random) are
stored here.
4. Installation-dependent default directories – Other directories where Python was
installed.

Python stops searching once it finds the module.

Checking Module Search Path


 Python stores the list of directories it searches in [Link].

Example:

import sys

print("Module Search Path:")


for path in [Link]:
print(path)

Output (Example):

Module Search Path:


C:\Users\YourName\Projects
C:\Python310\Lib\site-packages
C:\Python310\Lib
...

 The first path is usually the current directory.


 You can add new directories to [Link] if you want Python to search there.

Example of Path Searching


Suppose you have a module [Link] in a folder:

# [Link]
def hello(name):
return f"Hello, {name}!"

Case 1: Module in the same folder as the script

import greetings
print([Link]("Alice"))

✅ Works fine because Python searches the current directory first.

Case 2: Module in a different folder


import sys
[Link]('C:/Users/YourName/Modules') # add the folder to Python path

import greetings
print([Link]("Alice"))

 Now Python can find the module in the new folder.

You might also like