lOMoARcPSD|58603458
OPENING, CLOSING, READING AND WRITING IN FORMATTED FILE
FORMAT AND SORT DATA.
[Link] DATE
5 FILE OPERATIONS
AIM
To understand and demonstrate file operations in Python, including opening, closing, reading,
writing in a formatted manner, and sorting data stored in a file.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Opening and closing files (open(),
close())
Writing data in formatted manner
(write(), f-string)
Formatted file containing
Student data (name, roll Reading data from file (read(),
student data and a display of
number, marks) readlines())
sorted data
Parsing data into a list or dictionary
Sorting data using sorted() with key
function
ALGORITHM
Algorithm for file operations and sorting:
1. Start
2. Open a file in write mode to store data.
3. Write formatted data into the file (e.g., name, roll number, marks).
4. Close the file after writing.
5. Open the file in read mode to read the data.
6. Read all lines and store data in a suitable structure (list of dictionaries or tuples).
7. Sort the data based on a specific field (e.g., marks or name).
8. Display the sorted data in a formatted way.
9. Close the file.
10. End
PROGRAM
# FILE HANDLING AND SORTING DATA IN PYTHON
# Step 1: Open file in write mode and write formatted data
with open("[Link]", "w") as f:
[Link]("Name,Roll,Marks\n")
[Link]("Alice,101,85\n")
[Link]("Bob,102,92\n")
[Link]("Charlie,103,78\n")
[Link]("David,104,90\n")
# Step 2: Read data from file
students = []
with open("[Link]", "r") as f:
45
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
next(f) # Skip header line
for line in f:
name, roll, marks = [Link]().split(",")
[Link]({"Name": name, "Roll": int(roll), "Marks": int(marks)})
# Step 3: Sort data by Marks descending
sorted_students = sorted(students, key=lambda x: x["Marks"], reverse=True)
# Step 4: Display sorted data
print("Name\tRoll\tMarks")
for s in sorted_students:
print(f"{s['Name']}\t{s['Roll']}\t{s['Marks']}")
OUTPUT
Name Roll Marks
Bob 102 92
David 104 90
Alice 101 85
Charlie 103 78
RESULT
Thus, the file operation using python program executed successfully.
46
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6A NUMPY
AIM
To understand and demonstrate how the NumPy module in Python can be used to perform
efficient numerical computations, array operations, and data analysis to solve problems.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing the numpy module
Creating arrays from data
Performing arithmetic, statistical,
Computed results, processed
Numerical data (lists, and sorting operations
arrays, sorted data, or
sequences, or matrices) Using built-in NumPy functions for
statistical measures
numerical computations
ALGORITHM
Algorithm for solving problems using NumPy:
1. Start
2. Import the NumPy module using import numpy as np.
3. Create NumPy arrays from lists or using built-in functions ([Link](), [Link](),
[Link](), [Link]()).
4. Perform array operations:
o Arithmetic operations (+, -, *, /)
o Statistical operations (mean(), sum(), max(), min())
o Sorting arrays ([Link]())
5. Use NumPy functions for specific tasks:
o Reshape arrays (reshape())
o Generate random numbers ([Link])
o Perform matrix operations (dot(), transpose())
6. Display results.
7. End
PROGRAM
# USAGE OF NUMPY TO SOLVE PROBLEMS
import numpy as np
47
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
# Step 1: Create a NumPy array
data = [Link]([10, 20, 15, 30, 25])
print("Original Array:", data)
# Step 2: Perform arithmetic operations
print("Array + 5:", data + 5)
print("Array * 2:", data * 2)
# Step 3: Statistical operations
print("Sum:", [Link](data))
print("Mean:", [Link](data))
print("Maximum:", [Link](data))
print("Minimum:", [Link](data))
# Step 4: Sorting array
sorted_data = [Link](data)
print("Sorted Array:", sorted_data)
# Step 5: Reshape array
reshaped_data = [Link](1, 5)
print("Reshaped Array (1x5):\n", reshaped_data)
# Step 6: Random numbers
rand_array = [Link](1, 100, 5)
print("Random Array:", rand_array)
# Step 7: Matrix operations
matrix1 = [Link]([[1, 2], [3, 4]])
matrix2 = [Link]([[5, 6], [7, 8]])
product = [Link](matrix1, matrix2)
48
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
print("Matrix Product:\n", product)
OUTPUT
Original Array: [10 20 15 30 25]
Array + 5: [15 25 20 35 30]
Array * 2: [20 40 30 60 50]
Sum: 100
Mean: 20.0
Maximum: 30
Minimum: 10
Sorted Array: [10 15 20 25 30]
Reshaped Array (1x5):
[[10 20 15 30 25]]
Random Array: [74 7 79 64 53]
Matrix Product:
[[19 22]
[43 50]]
RESULT
Thus, the NumPy module using python program executed successfully.
49
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6B SCIPY
AIM
To understand and demonstrate the usage of the SciPy library in Python for performing
scientific and numerical computations, such as integration, differentiation, interpolation, and
solving linear algebra problems.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing SciPy modules
Defining functions or matrices
Performing numerical computations: Computed results such as
Numerical data (lists, integration, differentiation, integrals, solutions to
sequences, or matrices) optimization, linear algebra equations, interpolated
Displaying results values, or optimized results
ALGORITHM
Algorithm for solving problems using SciPy:
1. Start
2. Import the required SciPy submodules, e.g., [Link], [Link],
[Link].
3. Define the function or data on which operations are to be performed.
4. Use the appropriate SciPy function for the task:
o quad() for integration
o solve() for linear equations
o interpolate() for data interpolation
o optimize() for root-finding or optimization
5. Compute the results.
6. Display the results.
7. End
PROGRAM
# SCIPY OPERATIONS IN PYTHON
from scipy import integrate, optimize, linalg
import numpy as np
50
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
# 1. Integration of a function
def f(x):
return x**2
result, error = [Link](f, 0, 5) # integrate x^2 from 0 to 5
print("Integral of x^2 from 0 to 5:", result)
# 2. Solving a linear system: Ax = B
A = [Link]([[3, 1], [1, 2]])
B = [Link]([9, 8])
x = [Link](A, B)
print("Solution of linear system:", x)
# 3. Finding roots of an equation
def g(x):
return x**3 - 4*x - 9
root = [Link](g, 2) # initial guess = 2
print("Root of x^3 - 4x - 9 =", root[0])
# 4. Interpolation example
from [Link] import interp1d
x_points = [0, 1, 2, 3, 4]
y_points = [0, 2, 4, 6, 8]
f_interp = interp1d(x_points, y_points)
y_new = f_interp(2.5)
print("Interpolated value at x=2.5:", y_new)
51
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
OUTPUT
Integral of x^2 from 0 to 5: 41.66666666666666
Solution of linear system: [2. 3.]
Root of x^3 - 4x - 9 = 2.706527954497935
Interpolated value at x=2.5: 5.0
RESULT
Thus, the SciPy module using python program executed successfully.
52
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6C PANDAS
AIM
To understand and demonstrate how the Pandas library in Python can be used for data
manipulation, analysis, and solving problems using Series and DataFrames.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Creating Series and DataFrames
Accessing, adding, updating,
deleting data
Data in the form of Sorting and filtering data
Processed and analyzed data
lists, dictionaries, or Computing descriptive statistics
using Pandas operations
files (CSV/Excel) Reading/writing data from/to CSV or
Excel files
ALGORITHM
Algorithm for performing operations using Pandas:
1. Start
2. Import the pandas module using import pandas as pd.
3. Create a Series or DataFrame from lists, dictionaries, or CSV/Excel files.
4. Perform basic operations:
o Accessing rows and columns
o Selecting specific data using loc and iloc
o Adding, updating, or deleting columns
5. Perform data analysis:
o Descriptive statistics (mean(), sum(), min(), max())
o Sorting (sort_values())
o Filtering data based on conditions
6. Display results in tabular or formatted form.
7. End
53
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
PROGRAM
# PANDAS OPERATIONS IN PYTHON
import pandas as pd
# Step 1: Create DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie", "David"],
"Age": [25, 30, 22, 28],
"Marks": [85, 92, 78, 90]
}
df = [Link](data)
print("Original DataFrame:\n", df)
# Step 2: Access rows and columns
print("\nNames Column:\n", df["Name"])
print("\nFirst 2 rows:\n", [Link](2))
# Step 3: Add/Update/Delete columns
df["Grade"] = ["A", "A+", "B", "A"]
df["Age"] = df["Age"] + 1 # Update Age
[Link]("Grade", axis=1, inplace=True) # Delete Grade column
print("\nUpdated DataFrame:\n", df)
# Step 4: Data analysis
print("\nMean Marks:", df["Marks"].mean())
print("Maximum Marks:", df["Marks"].max())
print("Sorted by Marks descending:\n", df.sort_values(by="Marks", ascending=False))
# Step 5: Filtering data
high_scorers = df[df["Marks"] > 80]
print("\nStudents with Marks > 80:\n", high_scorers)
54
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
OUTPUT
Original DataFrame:
Name Age Marks
0 Alice 25 85
1 Bob 30 92
2 Charlie 22 78
3 David 28 90
Names Column:
0 Alice
1 Bob
2 Charlie
3 David
Name: Name, dtype: object
First 2 rows:
Name Age Marks
0 Alice 25 85
1 Bob 30 92
Updated DataFrame:
Name Age Marks
0 Alice 26 85
1 Bob 31 92
2 Charlie 23 78
3 David 29 90
Mean Marks: 86.25
Maximum Marks: 92
Sorted by Marks descending:
Name Age Marks
1 Bob 31 92
3 David 29 90
55
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
0 Alice 26 85
2 Charlie 23 78
Students with Marks > 80:
Name Age Marks
0 Alice 26 85
1 Bob 31 92
3 David 29 90
RESULT
Thus, the Pandas module using python program executed successfully.
56
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6D SCIKIT-LEARN
AIM
To understand and demonstrate how Scikit-learn (sklearn) can be used in Python for machine
learning tasks such as regression, classification, and model evaluation.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing datasets or creating
synthetic data
Data preprocessing and splitting
Dataset with features Selecting and training a model Predicted results and
(X) and labels (y) Making predictions evaluation metrics
Evaluating model performance
ALGORITHM
Algorithm for solving problems using Scikit-learn:
1. Start
2. Import required libraries: sklearn, numpy, pandas.
3. Load or create a dataset.
4. Preprocess data if necessary (handle missing values, encode categorical data).
5. Split dataset into training and testing sets using train_test_split.
6. Select a suitable machine learning model (e.g., LinearRegression,
DecisionTreeClassifier).
7. Train the model using fit() on training data.
8. Predict results on testing data using predict().
9. Evaluate the model using metrics like accuracy_score, mean_squared_error, etc.
10. Display results.
11. End
PROGRAM
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
57
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
# Sample dataset
X = [Link]([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]])
y = [Link]([2,4,5,4,5,6,7,8,9,10])
# Split dataset (40% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)
# Train Linear Regression model
model = LinearRegression()
[Link](X_train, y_train)
# Predict
y_pred = [Link](X_test)
# Evaluate
print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
print("R2 Score:", r2_score(y_test, y_pred))
print("Predicted values:", y_pred)
OUTPUT
Mean Squared Error: 0.26652892561983493
R2 Score: 0.9601452073839499
Predicted values: [8.81818182 3.09090909 6.36363636 2.27272727]
RESULT
Thus, the sklearn module using python program executed successfully
58
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6E BUILT-IN MODULES
AIM
To understand and demonstrate the usage of Python’s built-in modules for performing
common tasks efficiently, without the need to install external packages.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Mathematical operations (math)
Random number generation
Numbers, lists, (random) Computed results or
strings, or dates Date and time handling (datetime) processed data using built-in
depending on the task Statistical calculations (statistics) modules
File or directory operations (os)
ALGORITHM
1. Start
2. Identify the task to solve (math calculations, random numbers, date/time operations,
etc.)
3. Import the required built-in module (import module_name)
4. Use the module’s functions or classes to perform the task
5. Display the results
6. End
PROGRAM
# Demonstrating multiple Python built-in modules
import math
import random
import datetime
import statistics
import os
# Math module
num = 16
print("Square root:", [Link](num))
print("Factorial of 5:", [Link](5))
59
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
# Random module
print("Random integer between 1 and 10:", [Link](1, 10))
print("Random choice from list:", [Link]([10, 20, 30, 40]))
# Datetime module
now = [Link]()
print("Current date and time:", now)
# Statistics module
data = [10, 20, 30, 40, 50]
print("Mean:", [Link](data))
print("Median:", [Link](data))
# OS module
print("Current working directory:", [Link]())
print("List of files in directory:", [Link]())
OUTPUT
Square root: 4.0
Factorial of 5: 120
Random integer between 1 and 10: 4
Random choice from list: 30
Current date and time: 2025-09-05 22:36:49.342000
Mean: 30
Median: 30
Current working directory: /drive
List of files in directory: ['PYTHON [Link]', '[Link]', '[Link]',
'[Link]', 'data', 'notebooks']
RESULT
Thus, the Built-in modules using python program executed successfully.
60
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
[Link] DATE
6F BUILT-IN MODULES
AIM
To understand and demonstrate the creation and usage of user-defined modules in Python
to organize code into reusable components for solving problems efficiently.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Creating reusable functions or
classes
Importing the module in a main
Data (numbers, program Computed results using
strings, lists, etc.) to Calling module functions to functions defined in the
operate on perform tasks user-defined module
Organizing code for better
readability and maintainability
ALGORITHM
1. Start
2. Create a Python file (.py) containing functions, classes, or variables (this is the user-
defined module).
3. Save the module file in the same directory as the main program (or ensure it is in
Python path).
4. In the main program, import the module using:
o import module_name or
o from module_name import function_name
5. Use the functions or variables from the module to perform tasks.
6. Display the results.
7. End
PROGRAM
Step 1: Create module file [Link]
# [Link] - User-defined module
def add(a, b):
return a + b
61
Downloaded by Benilda Tony (mcbenilda14@[Link])
lOMoARcPSD|58603458
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 "Division by zero is not allowed"
Step 2: Main program using the module
# [Link] - Using user-defined module
import mymath # Import the user-defined module
x = 10
y=5
print("Addition:", [Link](x, y))
print("Subtraction:", [Link](x, y))
print("Multiplication:", [Link](x, y))
print("Division:", [Link](x, y))
OUTPUT:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
RESULT
Thus, the User-Defined modules using python program executed successfully.
62
Downloaded by Benilda Tony (mcbenilda14@[Link])