0% found this document useful (0 votes)
12 views5 pages

Understanding Python Modules and Usage

Uploaded by

mehak34208
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)
12 views5 pages

Understanding Python Modules and Usage

Uploaded by

mehak34208
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

Modules in Python

1. Introduction
 A module in Python is a file containing Python code (functions, classes, or variables) that you
can reuse in other programs.
 It helps in code reusability, organization, and modularity.

📁 Example:
A file named math_operations.py is a module if it contains Python code like:

def add(a, b):


return a + b

You can then import and use it in another file:

import math_operations
print(math_operations.add(5, 3))

2. Why Use Modules?


✅ To organize large programs into smaller, manageable parts.
✅ To reuse code across multiple projects.
✅ To avoid repetition of code.
✅ To share functionality (like math, time, os, etc.) easily.

3. Types of Modules
Python supports three types of modules:

Type Description Example


Built-in Modules Pre-installed with Python. math, os, sys, datetime, random
User-defined Modules Created by the user for specific tasks. [Link], file_utils.py
External Modules Installed using pip (third-party). numpy, pandas, requests

4. Importing Modules
Python provides several ways to import modules:

(a) Import the whole module


import math
print([Link](16))

🧠 You must use the module name before function name ([Link]).

(b) Import specific functions or variables


from math import sqrt, pi
print(sqrt(25))
print(pi)

🧠 You don’t need to prefix the module name.

(c) Import all contents (not recommended)


from math import *
print(sin(30))

⚠️May cause name conflicts if different modules have the same function names.

(d) Import with alias


import math as m
print([Link](2, 3))

🧠 Aliasing shortens names, useful for large libraries like import numpy as np.

5. The dir() Function


 Used to list all the names (functions, classes, variables) defined in a module.

import math
print(dir(math))

🧩 Example output:
['acos', 'asin', 'atan', 'ceil', 'cos', 'exp', 'floor', 'log', 'pi', 'sqrt', ...]

6. The __name__ Variable


 Every module has a built-in variable __name__.
 When a file runs directly, __name__ is set to '__main__'.
 When imported, __name__ is set to the module’s name.

Example:
# file: [Link]
def hello():
print("Hello, Python!")

if __name__ == "__main__":
print("Module executed directly")
else:
print("Module imported")

➡️Output when run directly:


Module executed directly
➡️Output when imported:
Module imported

🧠 Helps control which code runs during import.

7. Creating and Using User-Defined Modules


Step 1: Create a Python file ([Link])
def add(a, b):
return a + b

def sub(a, b):


return a - b

Step 2: Import and use it in another file ([Link])


import calculator
print([Link](10, 5))
print([Link](10, 5))

✅ Output:

15
5

8. Built-in Python Modules (Examples)


Module Purpose Example Function
math Mathematical functions [Link](16), [Link]
Module Purpose Example Function
random Random number generation [Link](1, 10)
datetime Date and time manipulation [Link]()
os Interact with operating system [Link](), [Link]()
sys Access system-specific parameters [Link], [Link]()
platform System and platform information [Link]()
statistics Mathematical statistics [Link]([1,2,3])

9. External Modules
Installed using pip (Python Package Installer).

Example:
pip install requests

Then import and use:

import requests
r = [Link]("[Link]
print(r.status_code)

🧠 You can view installed modules with:

pip list

10. Packages
 A package is a collection of related modules in a directory.
 Must contain a special file __init__.py (can be empty).
 Allows hierarchical module organization.

Example structure:
mypackage/
__init__.py
[Link]
[Link]

Usage:

from mypackage import mathops


[Link](5, 2)

11. Reloading a Module


 Sometimes after modifying a module, you may want to reload it without restarting Python.

import importlib
import mymodule
[Link](mymodule)

12. Summary
Concept Description Example
Module File with reusable Python code math, os, random
Import Bring module into program import math
Alias Rename for convenience import math as m
dir() List functions in module dir(math)
name Identifies if module run directly or imported if __name__ == "__main__"
Package Collection of modules [Link]

13. Advantages of Using Modules


✅ Encourages code reuse
✅ Easier maintenance
✅ Better organization of large programs
✅ Namespace management (avoids conflicts)
✅ Enables use of libraries and frameworks

14. Example Program


# file: [Link]
def square(n):
return n * n

def cube(n):
return n * n * n

# file: [Link]
import mymath as mm
print([Link](5))
print([Link](3))

🧾 Output:

25
27

You might also like