0% found this document useful (0 votes)
13 views17 pages

Understanding Python Modules and Packages

notes for exams

Uploaded by

nbrar5327
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)
13 views17 pages

Understanding Python Modules and Packages

notes for exams

Uploaded by

nbrar5327
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

🧩 Python Modules (Full

Explanation in Easy
Language)
🟢 1. Introduction
In Python, a module is simply a file that contains Python code — such as functions,
variables, or classes — that can be used in another program.
It helps in organizing large programs into small, manageable, and reusable pieces.

For example:
If you have a file named math_utils.py, it can contain functions like:

def add(a, b):


return a + b

Now you can use this file in another program by importing it.

🟢 2. Definition of a Module
👉 Definition:
A module in Python is a file containing Python definitions and statements, which
can be used in other programs by importing it.

📘 A module can contain:

 Functions
 Variables
 Classes
 Executable code

🧠 Example:
If we create a file named [Link]:

def say_hello(name):
print("Hello,", name)

Then, in another Python file:

import greet
greet.say_hello("Nav")

👉 Output:
Hello, Nav

Here, greet is a module.

🟢 3. Need of Modules (Why We Use


Modules)
Modules are very useful in Python for several reasons:

Reason Explanation
Once a module is written, it can be used in many
Reusability
programs. No need to write the same code again.
Better Large programs can be divided into smaller files,
Organization making them easier to manage.
Avoid Code
The same module can be reused multiple times.
Duplication
Easy If there’s an error, only one module file needs to
Maintenance be corrected.
Namespace Each module has its own namespace, which avoids
Management name conflicts.

💡 Example:
Python’s math module provides ready-made functions like sqrt(), sin(), cos(),
etc., which saves us from writing those functions ourselves.

🟢 4. Creating a Module
Creating a module is very simple.

Just write some Python code and save it as a .py file.

Example:

📄 File: [Link]

def add(a, b):


return a + b

def sub(a, b):


return a - b

pi = 3.14

Now you have created your own module named mymodule.


🟢 5. Importing a Module
To use the functions or variables from a module, we import it into another program.

There are different ways to import modules in Python:

(a) Simple Import


import mymodule
print([Link](5, 3))

Output:

(b) Import Specific Function


from mymodule import add
print(add(10, 5))

(c) Import with Alias


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

(d) Import All Functions


from mymodule import *
print(add(4, 2))
print(sub(6, 3))

🟢 6. Path Searching of a Module


When you use the import statement, Python searches for the module in a specific
order.

🔍 Search order:

Current Directory – The folder where your program is running.

PYTHONPATH Environment Variable – If set, Python looks here next.

Standard Library Directories – Built-in modules like math, os, etc.

Site-packages Directory – Installed third-party libraries (like NumPy).

📘 You can check all the search paths using:


import sys
print([Link])

This will display a list of directories where Python looks for modules.

🟢 7. Module Reloading
When a module is imported, Python loads it only once during the program’s
execution.
If you change the module file after importing, those changes won’t reflect
automatically.

To reload the module, use the importlib module.

Example:

import importlib
import mymodule

# Make some changes in [Link]


[Link](mymodule)

Now the updated version of the module will be reloaded.

🟢 8. Standard Modules in Python


Python provides a large collection of built-in standard modules that come pre-
installed with Python.
You can use them anytime by just importing them.

🔸 Some Common Standard Modules

Module
Use / Description Example Function
Name
math Mathematical operations [Link](), [Link]
random Generate random numbers [Link](1,10)
datetime Date and time operations [Link]()
os Interact with operating system [Link](), [Link]()
sys System-specific parameters [Link], [Link]()
Mathematical statistics
statistics [Link]()
functions
json JSON data handling [Link](), [Link]()

Example:
import math
print([Link](25))
print([Link])

Output:

5.0
3.141592653589793

🟢 9. Example: Complete Use of Module


📄 File: [Link]

def add(a, b):


return a + b

def mul(a, b):


return a * b

📄 File: [Link]

import calc
print([Link](4, 5))
print([Link](3, 6))

Output:

9
18

🟢 10. Advantages of Using Modules


✅ Code Reusability
✅ Easier Code Management
✅ Avoids Duplication
✅ Helps in Collaboration (teamwork)
✅ Provides Access to Large Standard Libraries

🟢 11. Summary Table


Concept Description Example
Module File containing Python code [Link]
Using module functions in a
Importing import math
program
Creating Writing a .py file with code [Link]
Path Search Where Python looks for modules [Link]
Concept Description Example
Reloading Re-import module after changes [Link]()
Standard
Built-in modules in Python math, os, sys
Modules

🧠 In short:

A Python module is a file that helps us organize,


reuse, and share code easily.
We can create our own modules, import built-in
modules, and even reload them if updated.

🧩 Python Packages
🟢 1. Introduction
In Python, when your project becomes large, it’s not practical to keep all your code in
one file or even one module.
To organize it better, Python provides Packages.

👉 A Package is simply a collection (folder) of modules grouped together in a


structured way.

It helps you:

 Organize code neatly into directories


 Avoid name conflicts
 Reuse code easily

📘 In short:

Module = Single File (.py file)


Package = Folder containing multiple modules

🟢 2. Definition of a Package
👉 Definition:
A package in Python is a collection of modules arranged in a directory (folder) that
also contains a special file called __init__.py.

This file tells Python that the folder should be treated as a package.
🟢 3. Structure of a Package
Let’s look at a simple example 👇

📂 Folder Structure:
myPackage/
__init__.py
[Link]
[Link]

📄 File: [Link]
def add(a, b):
return a + b

def sub(a, b):


return a - b

📄 File: [Link]
def multiply(a, b):
return a * b

def divide(a, b):


return a / b

📄 File: [Link]
# This can be empty or can contain package initialization code
print("myPackage is imported")

🟢 4. Creating and Using a Package


Step 1️⃣: Create a Package Folder

Make a folder named myPackage.

Step 2️⃣: Add Modules inside it

Add [Link] and [Link] files.

Step 3️⃣: Add __init__.py file

This marks the folder as a package.

Step 4️⃣: Use the Package in Another Program


# [Link]
from myPackage import addsub, multiplydivide

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

Output:

myPackage is imported
8
8

✅ Package successfully imported and used!

🟢 5. What is __init__.py File?


It is a special file that tells Python that the directory should be treated as a
package.

It can be empty or can contain initialization code (like importing specific


modules).

Example:

# __init__.py
from .addsub import add
from .multiplydivide import multiply

Now you can directly use:

from myPackage import add, multiply

🟢 6. Importing from a Package


There are different ways to import modules from a package:

Import Type Example Usage


Import full import [Link](
module [Link] 3,2)
Import specific from [Link]
add(3,2)
function import add
Import all from myPackage import
All functions available
modules *
import
Import with alias [Link](3,2)
[Link] as m
🟢 7. Nested Packages (Sub-Packages)
A package can also contain other packages inside it — these are called sub-
packages.

Example folder structure 👇

Company/
__init__.py
HR/
__init__.py
[Link]
Sales/
__init__.py
[Link]

Using sub-packages:

from [Link] import salary


from [Link] import customers

🟢 8. Advantages of Packages
Advantage Explanation
Code Packages help divide code into folders and
Organization modules, making it easier to manage.
Once created, packages can be reused in
Reusability
different projects.
Avoids Name Modules inside different packages can have the
Conflicts same names safely.
Easy Fixing or updating code is simpler since it’s
Maintenance modular.
Supports Large Ideal for structuring big programs with multiple
Projects components.

🟢 9. Example: Using a Built-in Python


Package
Python itself has many standard packages.

Example:

import math
print([Link](16))

Here, math is a standard package/module provided by Python.


Other examples of built-in packages:

 os (for operating system operations)


 sys (for system-level functions
 random (for generating random numbers)
 datetime (for date and time handling)

🟢 10. Installing External Packages


We can also use third-party packages created by others.
They are usually installed using pip (Python’s package manager).

Example:
pip install numpy
pip install pandas

Then you can use them:

import numpy as np
import pandas as pd

✅ These are powerful libraries for data science and analysis.

🟢 11. Real-Life Example


Suppose you are developing a Banking System.

You can organize it using packages like this:

BankSystem/
__init__.py
Account/
__init__.py
[Link]
[Link]
Transactions/
__init__.py
[Link]
[Link]

Then in your main file:

from [Link] import savings


from [Link] import deposit

savings.create_account()
deposit.add_money()
This keeps your project well organized and professional.

🟢 12. Difference Between Module and


Package
Feature Module Package
A single Python A folder containing multiple
Definition
file (.py) modules and __init__.py
File Type .py file Directory (folder)
Example [Link] math/
Usage Import directly Import using folder name
Organization
Small Higher (collection of modules)
Level

A Python Package is a directory that groups


related modules together.
It helps you organize, reuse, and maintain code
efficiently, especially in large projects.

⚙️Exception Handling in
Python

🟢 1. Introduction
In programming, sometimes an error occurs during program execution — for
example:

 Dividing a number by zero


 Opening a file that doesn’t exist
 Using a variable that’s not defined

These runtime errors are called exceptions.


If not handled properly, they can stop the whole program.

👉 Exception Handling means detecting and dealing with errors in a safe and
controlled way, without stopping the program abruptly.
🟢 2. What is an Exception?
✅ Definition:

An Exception is an error that occurs during program execution which disrupts the
normal flow of instructions.

For example:

a = 10
b = 0
print(a / b)

❌ Output:

ZeroDivisionError: division by zero

Here, the program stops because of an exception.

🟢 3. Why Use Exception Handling?


Reason Explanation
To prevent The program won’t stop suddenly if an error
crashes occurs.
To handle errors
We can show friendly messages to the user.
smoothly
To maintain Allows the program to continue executing even
program flow after an error.
To debug easily Helps locate and fix errors effectively.

🟢 4. Keywords Used in Exception


Handling
Python provides five main keywords for handling exceptions:

Keywo
Purpose
rd
try Block of code that may cause an exception
except Handles the exception if it occurs
else Executes if there is no exception
Executes always, whether there is an exception or
finally
not
raise Used to manually raise an exception
🟢 5. Try-Except Block
The try-except block is the most common form of exception handling.

🧠 Syntax:
try:
# Code that may cause an exception
except:
# Code to handle the exception

📘 Example:
try:
a = 10
b = 0
print(a / b)
except:
print("Error: Division by zero is not allowed.")

✅ Output:

Error: Division by zero is not allowed.

🧩 Explanation:

The code inside try runs first.

If an exception occurs, the control jumps to the except block.

🟢 6. Try-Except-Else Block
If no exception occurs, the code inside the else block executes.

🧠 Syntax:
try:
# Code that may cause an error
except:
# Runs if error occurs
else:
# Runs if no error occurs

📘 Example:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Please enter a valid number.")
else:
print("No error occurred.")

✅ Output (if valid input):

Enter a number: 10
You entered: 10
No error occurred.

🟢 7. Try-Except-Finally Block
The finally block always executes, whether an error occurs or not.
It is usually used for clean-up actions like closing files or releasing resources.

🧠 Syntax:
try:
# Code that may cause an exception
except:
# Code to handle the exception
finally:
# Code that will always execute

📘 Example:
try:
f = open("[Link]", "r")
data = [Link]()
except FileNotFoundError:
print("File not found!")
finally:
print("Program execution finished.")

✅ Output:

File not found!


Program execution finished.

🟢 8. Try-Except-Else-Finally (All
Together)
You can use all four blocks together.

📘 Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
else:
print("Result:", result)
finally:
print("Thank you for using the program.")

✅ Output Example 1:

Enter a number: 5
Result: 2.0
Thank you for using the program.

✅ Output Example 2:

Enter a number: 0
Cannot divide by zero!
Thank you for using the program.

🟢 9. Multiple Except Blocks


We can handle different types of exceptions using multiple except blocks.

📘 Example:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("You can’t divide by zero!")
except ValueError:
print("Please enter valid numbers only!")

✅ Output (if invalid input):

Please enter valid numbers only!

🟢 10. Raising Exceptions (raise


Statement)
Sometimes, we may want to manually trigger an exception.
For that, we use the raise statement.

🧠 Syntax:
raise ExceptionType("Error message")

📘 Example:
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be 18 or older!")
else:
print("Welcome!")

✅ Output:

Enter your age: 16


ValueError: You must be 18 or older!

🟢 11. Hierarchy of Exceptions in Python


All exceptions in Python are classes, and they are organized in a hierarchy (tree
structure).

📘 Top of the hierarchy:

BaseException
├── SystemExit
├── KeyboardInterrupt
├── Exception
├── ArithmeticError
│ ├── ZeroDivisionError
│ ├── OverflowError
│ └── FloatingPointError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── ValueError
├── TypeError
├── FileNotFoundError
└── ImportError

✅ Note:
Most user-defined exceptions are derived from the Exception class.

🟢 12. Adding (Creating) User-Defined


Exceptions
Python also allows us to create our own custom exceptions.

We do this by creating a new class that inherits from the built-in Exception class.

📘 Example:
class AgeTooSmallError(Exception):
pass # no additional code needed

try:
age = int(input("Enter your age: "))
if age < 18:
raise AgeTooSmallError("Age must be 18 or above!")
except AgeTooSmallError as e:
print("Custom Exception:", e)

✅ Output:

Enter your age: 15


Custom Exception: Age must be 18 or above!

🟢 14. Advantages of Exception Handling


✅ Prevents program crashes
✅ Improves program stability
✅ Makes debugging easier
✅ Allows proper resource cleanup
✅ Helps in user-friendly error messages

🧠 In Short:
Exception Handling helps us manage runtime errors
gracefully using
try, except, else, finally, and raise.
It keeps the program error-free, user-friendly, and
reliable.

You might also like