Python Modules and Packages — Full Notes
Python Modules and Packages — Full Notes
What is a Module in Python?
A module is simply a Python file (.py) that contains functions, variables, or classes that you can reuse in other programs.
✅ Helps in organizing code
✅ Promotes reusability
✅ Keeps code manageable
Example:
math_operations.py (This is a module you can import)
def add(x, y):
return x + y
main.py
import math_operations
print(math_operations.add(5, 3)) # Output: 8
What is a Package in Python?
A package is a folder that contains multiple modules (Python files), and has a special file called __init__.py.
✅ Used to organize related modules
✅ __init__.py makes it a package (can be empty or have setup code)
Structure of a Package:
my_package/
│
├── __init__.py
├── module1.py
└── module2.py
To use a function from module1.py:
from my_package import module1
module1.function_name()
Importing Modules in Python
✅ Different ways to import:
import math # Full module
from math import sqrt # Specific function
import math as m # Alias
print(math.sqrt(16)) # Using full module
print(sqrt(16)) # Direct function
print(m.sqrt(16)) # Using alias
Built-in Modules and Standard Library Examples
✅ 1. random Module – Working with Random Numbers
import random
print(random.randint(1, 10)) # Random int between 1 and 10
print(random.choice(['a', 'b'])) # Randomly pick an element
print(random.random()) # Random float [0.0, 1.0)
✅ 2. time Module – Working with Time
import time
print("Start")
time.sleep(2) # Pause for 2 seconds
print("End")
print(time.time()) # Seconds since epoch
print(time.ctime()) # Current time in readable format
✅ 3. datetime Module – Dates and Times
import datetime
now = datetime.datetime.now()
print("Current Date & Time:", now)
today = datetime.date.today()
print("Today's Date:", today)
# Creating a specific date
d = datetime.date(2023, 9, 25)
print("Custom Date:", d)
✅ 4. calendar Module – Calendar Functions
import calendar
print(calendar.month(2025, 9)) # Display September 2025
print(calendar.isleap(2024)) # Check if year is a leap year
✅ 5. sys Module – System-Specific Info
import sys
print("Python Version:", sys.version)
print("Platform:", sys.platform)
print("Command-line arguments:", sys.argv)
User-Defined Modules
✅ Example:
my_math.py
def square(x):
return x * x
main.py
import my_math
print(my_math.square(4)) # Output: 16
💡 Save both files in the same folder.
User-Defined Packages
✅ Folder Structure:
math_pkg/
│
├── __init__.py
├── operations.py
└── algebra.py
operations.py
def add(a, b):
return a + b
main.py
from math_pkg import operations
print(operations.add(10, 5)) # Output: 15
Pre-defined Packages in Python
These are part of the Python Standard Library or third-party packages you install using pip.
✅ Examples:
Defined Functions in Modules
You can define any number of functions in a module:
# my_utils.py
def greet(name):
print("Hello,", name)
def square(x):
return x * x
Then import and use:
import my_utils
my_utils.greet("Alice")
print(my_utils.square(3)) # Output: 9
PART 1 : Programs for modules :
Exercise 1: Using the random Module
Write a program that simulates rolling a dice 5 times and prints the results.
import random
print("Rolling the dice 5 times:")
for i in range(5):
roll = random.randint(1, 6)
print(f"Roll {i+1}: {roll}")
Exercise 2: Use datetime to Print Birthday Countdown
Ask the user for their birthday and calculate how many days are left.
import datetime
birth_month = int(input("Enter your birth month (1-12): "))
birth_day = int(input("Enter your birth day (1-31): "))
today = datetime.date.today()
birthday = datetime.date(today.year, birth_month, birth_day)
if birthday < today:
birthday = datetime.date(today.year + 1, birth_month, birth_day)
days_left = (birthday - today).days
print(f"Your birthday is in {days_left} days!")
Exercise 3: Create and Use a Simple Module
Create a file named math_utils.py with this code:
# math_utils.py
def square(x):
return x * x
def cube(x):
return x * x * x
Create another file in the same folder:
# main.py
import math_utils
print(math_utils.square(5)) # Output: 25
print(math_utils.cube(3)) # Output: 27
Exercise 4: Using calendar to Show a Month
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month (1-12): "))
print(calendar.month(year, month))
PART 2: Create Your Own Python Package (Step-by-Step) :
Folder Structure:
my_package/
│
├── __init__.py
├── calculator.py
└── greetings.py
Step-by-Step:
1. Create the package folder:
Name it my_package
2. Inside that folder, create __init__.py
You can leave it empty or add this:
# my_package/__init__.py
print("My package is being loaded.")
3. Create calculator.py
# my_package/calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
4. Create greetings.py
# my_package/greetings.py
def hello(name):
return f"Hello, {name}!"
def goodbye(name):
return f"Goodbye, {name}!"
5. Create a separate file main.py
# main.py
from my_package import calculator, greetings
print(calculator.add(10, 5)) # Output: 15
print(calculator.multiply(3, 4)) # Output: 12
print(greetings.hello("Alice")) # Output: Hello, Alice!
print(greetings.goodbye("Alice")) # Output: Goodbye, Alice!
Part 3 :
1 NumPy – Numerical Python
Example: Create an array and do basic math
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Multiply all elements by 2
arr2 = arr * 2
print("Original array:", arr)
print("Doubled array:", arr2)
2 SciPy – Scientific Computing
Example: Use scipy to calculate integration
from scipy import integrate
# Define a function to integrate
def f(x):
return x**2
# Integrate f(x) from 0 to 2
result, _ = integrate.quad(f, 0, 2)
print("Integral of x^2 from 0 to 2:", result)
3 SciPy.linalg – Linear Algebra
Example: Solve a system of linear equations
from scipy.linalg import solve
import numpy as np
# 2x + 3y = 8
# 3x + 4y = 11
A = np.array([[2, 3], [3, 4]])
B = np.array([8, 11])
result = solve(A, B)
print("Solution [x, y]:", result)
4 Matplotlib – Plotting and Graphs
Example: Plot a line graph
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()
This will open a window with the graph.
5 Pandas – Series Data Structure
Example: Create and use a Series
import pandas as pd
# Create a series
data = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print("Series:")
print(data)
# Access a value
print("Value at index 'b':", data["b"])
6 Anonymous Function (Lambda Function)
Example: Square a number using lambda
# Lambda function to square a number
square = lambda x: x * x
print("Square of 5 is:", square(5))
Lambda with map() for lists
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print("Original:", numbers)
print("Squared:", squared)
**** Programs to do in the Lab ****
1. NumPy – Working with Arrays
import numpy as np
# Create an array of numbers
arr = np.array([10, 20, 30, 40])
# Multiply all elements by 2
doubled = arr * 2
# Find sum and mean
print("Array:", arr)
print("Doubled:", doubled)
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
2. SciPy – Integration Example
from scipy import integrate
# Define a function to integrate: f(x) = x^2
def f(x):
return x**2
# Integrate f(x) from 0 to 3
result, error = integrate.quad(f, 0, 3)
print("Integral of x^2 from 0 to 3 is:", result)
3. SciPy.linalg – Solving Linear Equations
Equation system:
2x + y = 5
4x + 3y = 11
from scipy.linalg import solve
import numpy as np
# Coefficients matrix
A = np.array([[2, 1], [4, 3]])
# Right-hand side
B = np.array([5, 11])
# Solve
solution = solve(A, B)
print("Solution [x, y]:", solution)
4. Matplotlib – Line Graph Example
import matplotlib.pyplot as plt
# Sample data
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]
# Plotting
plt.plot(x, y, color='blue', marker='o')
plt.title("Line Plot of y = x^2")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()
5. Pandas Series – One-Dimensional Data
import pandas as pd
# Create a Series
marks = pd.Series([90, 85, 88, 76], index=["Alice", "Bob", "Charlie", "David"])
# Display the Series
print("Marks of students:")
print(marks)
# Access a specific value
print("Marks of Bob:", marks["Bob"])
# Find average marks
print("Average:", marks.mean())
6. Lambda Functions – Anonymous Function
Example 1: Square a number
square = lambda x: x * x
print("Square of 5 is:", square(5))
Example 2: Use map() with lambda to square a list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x * x, numbers))
print("Original:", numbers)
print("Squared:", squared)
Mini Project : Student Marks Analyzer
Combine NumPy, Pandas, and Matplotlib:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
names = ["Alice", "Bob", "Charlie", "David"]
marks = np.array([85, 92, 78, 88])
# Create a Pandas Series
student_marks = pd.Series(marks, index=names)
# Print stats
print("Average marks:", student_marks.mean())
print("Highest marks:", student_marks.max())
# Plot
student_marks.plot(kind='bar', color='green')
plt.title("Student Marks")
plt.ylabel("Marks")
plt.xlabel("Students")
plt.grid(True)
plt.show()
Comments
Post a Comment