0% found this document useful (0 votes)
3 views48 pages

Python

The document outlines the regulations and practical exercises for the Computer Science and Engineering department at Karpaga Vinayaga College of Engineering and Technology. It includes various programming tasks such as arithmetic operations, string analysis, data handling with DataFrames, and machine learning models. Each exercise provides an aim, algorithm, Python code, sample input/output, and confirms successful execution.

Uploaded by

valarmathi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Python

The document outlines the regulations and practical exercises for the Computer Science and Engineering department at Karpaga Vinayaga College of Engineering and Technology. It includes various programming tasks such as arithmetic operations, string analysis, data handling with DataFrames, and machine learning models. Each exercise provides an aim, algorithm, Python code, sample input/output, and confirms successful execution.

Uploaded by

valarmathi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

KARPAGA VINAYAGA

COLLEGE OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

REGULATIONS- 2021

NAME:

REGNO:

DEPT:

YEAR/SEM:
INDEX

[Link] Date Title Pg. no Marks Signature

1 Arithmetic Operations using Function

2 Count Vowels and Consonants in a String

Print Even Numbers from a List


3

4 Count Occurrences in a Tuple

Dictionary Iteration (Keys & Values)


5

DataFrame Creation & Handling Missing


6 Values

7 DataFrame Statistics & Column Operations

8 2D Array Operations & Statistics

9 Load CSV & Data Exploration

10 SciPy Mathematical Functions

11 Function Minimization using SciPy


12 Linear Regression Model

13 K-Nearest Neighbors (KNN)

14 K-Means Clustering

15 Moving Average Forecast

16 Data Visualization (Matplotlib&Seaborn)

17 Django Web Application (CRUD & API)

18 Flask Web Application

19 E-Governance Dataset Analysis

20 Mini Project – E-Governance Application

Dataset Completeness & Consistency


21 Analysis

22 IT Service Mapping & Monitoring

23 Model Accuracy Evaluation

24 Gantt Chart for Project Planning

25 Risk Evaluation in Dataset


Ex No.01 ARITHMETIC OPERATION USING FUNCTION
Date:

Aim

To create a function that takes two numbers as input and returns their sum, difference, product,
and quotient.

Algorithm

1. Start the program.

2. Define a function calculate_operations (a, b).

3. Inside the function:

o Compute sum = a + b

o Compute difference = a - b

o Compute product = a × b

o If b ≠ 0:

 Compute quotient = a ÷ b

o Else:

 Set quotient as "Undefined (division by zero)"

4. Return all four results.

5. Read two input numbers from the user.

6. Call the function with given inputs.

7. Display the results.

8. Stop the program.


Program (Python)

def calculate_operations(a, b):


sum_result = a + b
difference = a - b
product = a * b

if b != 0:
quotient = a / b
else:
quotient = "Undefined (division by zero)"

return sum_result, difference, product, quotient

# Input
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

# Function call
sum_result, difference, product, quotient = calculate_operations(a, b)

# Output
print("Sum:", sum_result)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)

Sample Input :
Enter first number: 10
Enter second number: 5

Sample Output :
Sum: 15.0
Difference: 5.0
Product: 50.0
Quotient: 2.0

Result :

Hence the program is Compiled and Verified.

Ex No.02 COUNT VOWELS AND CONSONANTS IN A STRING


Date:
Aim

To write a program that counts the number of vowels and consonants in a given string.

Algorithm

1. Start the program.


2. Read a string from the user.
3. Initialize two counters: vowels = 0, consonants = 0.
4. Convert the string to lowercase (optional for easy comparison).
5. For each character in the string:
o If the character is a vowel (a, e, i, o, u), increment vowel count.
o Else if the character is an alphabet, increment consonant count.
6. Display the number of vowels and consonants.
7. Stop the program

Program (Python)

defcount_vowels_consonants(text):
vowels = "aeiouAEIOU"
v_count = 0
c_count = 0

for ch in text:
if [Link](): # check if character is alphabet
if ch in vowels:
v_count += 1
else:
c_count += 1

return v_count, c_count

# Input
text = input("Enter a string: ")
# Function call
vowels, consonants = count_vowels_consonants(text)

# Output
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Input
Enter a string: Hello World

Output
Number of vowels: 3
Number of consonants: 7

Result

Thus, the program to count the number of vowels and consonants in a given string was successfully
implemented and executed.
Ex No.03 PRINT EVEN NUMBERS FROM A LIST
Date:

Aim

To write a program that prints all even numbers from a given list using a loop.

Algorithm

1. Start the program.


2. Read a list of numbers from the user.
3. Traverse each element in the list using a loop.
4. For each element:
o Check if the number is divisible by 2 (number % 2 == 0).
o If true, print the number.
5. Stop the program.

Program (Python)
# Function to print even numbers
defprint_even_numbers(lst):
print("Even numbers in the list are:")
for num in lst:
if num % 2 == 0:
print(num, end=" ")

# Input
lst = list(map(int, input("Enter list elements separated by space:
").split()))

# Function call
print_even_numbers(lst)

Input
Enter list elements separated by space: 1 2 3 4 5 6 7 8
Output
Even numbers in the list are:
2 4 6 8

Result

Thus, the program to print all even numbers from a list using a loop was successfully implemented
and executed.
Ex No.04 COUNT OCCURANCES OF AN ELEMENT IN A TUPLE
Date:

Aim

To write a program that counts the number of occurrences of a specific element in a given tuple.

Algorithm

1. Start the program.


2. Read tuple elements from the user.
3. Read the element to be searched.
4. Initialize a counter variable count = 0.
5. Traverse each element in the tuple:
o If the element matches the given value, increment count.
6. Display the count.
7. Stop the program.

Program (Python)
# Function to count occurrences
defcount_occurrences(tup, element):
count = 0
for item in tup:
if item == element:
count += 1
return count

# Input
tup = tuple(map(int, input("Enter tuple elements separated by space:
").split()))
element = int(input("Enter element to count: "))

# Function call
result = count_occurrences(tup, element)

# Output
print("Number of occurrences:", result)
Input
Enter tuple elements separated by space: 1 2 3 2 4 2 5
Enter element to count: 2

Output
Number of occurrences: 3

Result

Thus, the program to count the number of occurrences of a specific element in a tuple was
successfully implemented and executed.

Ex No.05 ITERATE THROUGH A DICTIONARY AND PRIMARY KEY


Date: AND
VALUES SEPERATELY
Aim

To write a program that iterates through a dictionary and prints its keys and values separately.

Algorithm

1. Start the program.


2. Read key-value pairs from the user and store them in a dictionary.
3. Display all keys:
o Traverse the dictionary using a loop and print each key.
4. Display all values:
o Traverse the dictionary using a loop and print each value.
5. Stop the program.

Program (Python)
# Function to print keys and values
defprint_keys_values(d):
print("Keys:")
for key in [Link]():
print(key)

print("Values:")
for value in [Link]():
print(value)

# Input
n = int(input("Enter number of elements: "))
d = {}

for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value

# Function call

print_keys_values(d)
Input
Enter number of elements: 3
Enter key: a
Enter value: 10
Enter key: b
Enter value: 20
Enter key: c
Enter value: 30

Output
Keys:
a
b
c
Values:
10
20
30

Result

Thus, the program to iterate through a dictionary and print keys and values separately was
successfully implemented and executed.

Ex No.06 CREATE A DATA FRAME AND HANDLE MISSING VALUES


Date:
Aim

To create a DataFrame from a dictionary and handle missing values in the DataFrame.

Algorithm

1. Start the program.


2. Import the pandas library.
3. Create a dictionary with some missing values (e.g., None or NaN).
4. Convert the dictionary into a DataFrame.
5. Display the DataFrame.
6. Check for missing values using isnull().
7. Handle missing values:
o Either remove missing values using dropna()
o Or fill missing values using fillna()
8. Display the updated DataFrame.
9. Stop the program.

Program (Python)
import pandas as pd

# Creating dictionary with missing values


data = {
"Name": ["Alice", "Bob", "Charlie", "David"],
"Age": [25, None, 30, 22],
"Marks": [85, 90, None, 88]
}

# Creating DataFrame
df = [Link](data)

# Display DataFrame
print("Original DataFrame:")
print(df)

# Check missing values


print("\nMissing Values:")
print([Link]())

# Handling missing values (filling with 0)


df_filled = [Link](0)

print("\nDataFrame after handling missing values:")


print(df_filled)
Input

(No user input required — data is predefined in the program)

Output
Original DataFrame:
Name Age Marks
0 Alice 25.0 85.0
1 Bob NaN 90.0
2 Charlie 30.0 NaN
3 David 22.0 88.0

Missing Values:
Name Age Marks
0 False FalseFalse
1 False True False
2 False False True
3 False FalseFalse

DataFrame after handling missing values:


Name Age Marks
0 Alice 25.0 85.0
1 Bob 0.0 90.0
2 Charlie 30.0 0.0
3 David 22.0 88.0

Result

Thus, the DataFrame was successfully created from a dictionary and missing values were identified
and handled using appropriate methods.

Ex No.07 BASIC STATISTICS AND ADDING NEW COLUMN IN


Date: DATAFRAME
Aim

To calculate basic statistics of a DataFrame column and add a new column based on existing
columns.

Algorithm

1. Start the program.


2. Import the pandas library.
3. Create a DataFrame using a dictionary.
4. Calculate statistics (mean, sum, min, max).
5. Add a new column using existing columns.
6. Display the updated DataFrame.
7. Stop the program.

Program (Python)
import pandas as pd

# Create DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Marks1": [80, 75, 90],
"Marks2": [85, 70, 95]
}

df = [Link](data)

# Basic statistics
print("Mean Marks1:", df["Marks1"].mean())
print("Sum Marks1:", df["Marks1"].sum())
print("Max Marks1:", df["Marks1"].max())
print("Min Marks1:", df["Marks1"].min())

# Add new column (Total)


df["Total"] = df["Marks1"] + df["Marks2"]

print("\nUpdatedDataFrame:")
print(df)

Input
(No user input required)

Output
Mean Marks1: 81.67
Sum Marks1: 245
Max Marks1: 90
Min Marks1: 75

Updated DataFrame:
Name Marks1 Marks2 Total
0 Alice 80 85 165
1 Bob 75 70 145
2 Charlie 90 95 185

Result

Thus, basic statistics were calculated and a new column was successfully added.
Aim

To create a 2D array and perform basic operations, and calculate mean and standard deviation.

Algorithm

1. Start the program.


2. Import numpy library.
3. Create a 2D array.
4. Perform operations (sum, transpose).
5. Calculate mean and standard deviation.
6. Display results.
7. Stop the program.

Program (Python)
import numpy as np

# Create 2D array
arr = [Link]([[1, 2, 3],
[4, 5, 6]])

print("Array:\n", arr)

# Operations
print("Sum:", [Link]())
print("Transpose:\n", arr.T)

# Statistics
print("Mean:", [Link]())
print("Standard Deviation:", [Link]())

Input

(No user input required)

Output
Array:
[[1 2 3]
[4 5 6]]

Sum: 21
Transpose:
[[1 4]
[2 5]
[3 6]]

Mean: 3.5
Standard Deviation: 1.7078

Result

Thus, the 2D array operations and statistical measures were successfully performed.
Aim

To load a CSV file, display first few records, and find total number of entries.

Algorithm

1. Start the program.


2. Import pandas library.
3. Load CSV file using read_csv().
4. Display first few rows using head().
5. Find total entries using len() or shape.
6. Display results.
7. Stop the program.

Program (Python)
import pandas as pd

# Load CSV file


df = pd.read_csv("[Link]")

# Display first few records


print("First 5 rows:")
print([Link]())

# Total entries
print("\nTotal number of entries:", len(df))

Input

Example CSV file: [Link]

Name,Age,Marks
Alice,20,85
Bob,21,78
Charlie,19,90
David,22,88
Eva,20,76

Output
First 5 rows:
Name Age Marks
0 Alice 20 85
1 Bob 21 78
2 Charlie 19 90
3 David 22 88
4 Eva 20 76

Total number of entries: 5

Result

Thus, the CSV file was successfully loaded, explored, and total entries were identified.
Aim

To calculate factorial, square root, and exponential using SciPy.

Algorithm

1. Start the program.


2. Import required functions from SciPy and NumPy.
3. Read input number.
4. Calculate factorial using [Link]().
5. Calculate square root using [Link]().
6. Calculate exponential using [Link]().
7. Display results.
8. Stop the program.

Program (Python)
from [Link] import factorial
import numpy as np

num = int(input("Enter a number: "))

print("Factorial:", factorial(num))
print("Square Root:", [Link](num))
print("Exponential:", [Link](num))

Input
Enter a number: 5

Output
Factorial: 120.0
Square Root: 2.236
Exponential: 148.41

Result

Thus, factorial, square root, and exponential were calculated successfully.


Aim

To find the minimum value of a simple function.

Algorithm

1. Start the program.


2. Import minimize from SciPy.
3. Define a function (e.g., f(x) = x² + 3x + 2).
4. Provide initial guess.
5. Apply minimize function.
6. Display minimum value.
7. Stop the program.

Program (Python)
from [Link] import minimize

# Function
deffunc(x):
return x**2 + 3*x + 2

result = minimize(func, x0=0)

print("Minimum value:", [Link])


print("At x =", result.x)

Input

(No user input required)

Output
Minimum value: -0.25
At x = [-1.5]

Result

Thus, the minimum of the function was successfully determined.


Aim

To perform linear regression on sample data.

Algorithm

1. Start the program.


2. Import required libraries.
3. Define input (X) and output (Y) data.
4. Fit regression model.
5. Display slope and intercept.
6. Stop the program.

Program (Python)
import numpy as np
from sklearn.linear_model import LinearRegression

X = [Link]([[1], [2], [3], [4]])


Y = [Link]([2, 4, 6, 8])

model = LinearRegression()
[Link](X, Y)

print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)

Input

(No user input required)

Output
Slope: 2.0
Intercept: 0.0

Result
Thus, linear regression was successfully performed.

Aim

To classify points using K-Nearest Neighbors.

Algorithm

1. Start the program.


2. Import KNN classifier.
3. Define training data and labels.
4. Train the model.
5. Predict new data point.
6. Display result.
7. Stop the program.

Program (Python)
from [Link] import KNeighborsClassifier

X = [[1], [2], [3], [4]]


Y = [0, 0, 1, 1]

model = KNeighborsClassifier(n_neighbors=3)
[Link](X, Y)

prediction = [Link]([[2.5]])
print("Predicted class:", prediction)

Input

(No user input required)

Output
Predicted class: [0]

Result
Thus, classification using KNN was successfully performed.

Aim

To perform K-Means clustering on 2D data.

Algorithm

1. Start the program.


2. Import KMeans.
3. Define dataset.
4. Apply KMeans clustering.
5. Display cluster labels.
6. Stop the program.

Program (Python)
import numpy as np
from [Link] import KMeans

X = [Link]([[1,2], [1,4], [5,6], [6,8]])

kmeans = KMeans(n_clusters=2)
[Link](X)

print("Cluster labels:", kmeans.labels_)

Input

(No user input required)

Output
Cluster labels: [0 0 1 1]

Result

Thus, K-Means clustering was successfully performed.


Aim

To forecast values using a simple moving average.

Algorithm

1. Start the program.


2. Import pandas.
3. Create time series data.
4. Apply rolling mean.
5. Display results.
6. Stop the program.

Program (Python)
import pandas as pd

data = [10, 20, 30, 40, 50]


series = [Link](data)

moving_avg = [Link](window=3).mean()

print("Moving Average:\n", moving_avg)

Input

(No user input required)

Output
Moving Average:
0 NaN
1 NaN
2 20.0
3 30.0
4 40.0
dtype: float64
Result

Thus, forecasting using a simple moving average was successfully performed.

E-Governance Dataset Analysis


Aim
To analyze an E-Governance dataset by loading, cleaning, applying linear regression, performing
clustering, and visualizing trends.

Algorithm
1. Start the program.
2. Import required libraries (Pandas, NumPy, Matplotlib, Scikit-learn).
3. Load the dataset using Pandas.
4. Explore the dataset using head(), info(), and describe().
5. Clean the data:
o Handle missing values using fillna() or dropna().
6. Apply Linear Regression:
o Select independent and dependent variables.
o Train the model and predict values.
7. Perform Clustering:
o Select relevant features.
o Apply K-Means clustering.
8. Visualize data:
o Use line plots, bar charts, and histograms.
9. Display results.
10. Stop the program.

Program (Python)
import pandas as pd
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from [Link] import KMeans

# Step 1: Load dataset


df = pd.read_csv("egov_data.csv")

# Step 2: Explore data


print("First 5 rows:\n", [Link]())
print("\nDataset Info:\n")
print([Link]())

# Step 3: Data Cleaning


df = [Link]([Link](numeric_only=True))

# Step 4: Linear Regression


# Example: Predict 'Services_Used' based on 'Population'
X = df[["Population"]]
y = df["Services_Used"]

model = LinearRegression()
[Link](X, y)

predictions = [Link](X)

print("\nRegression Coefficient:", model.coef_)


print("Intercept:", model.intercept_)

# Step 5: Clustering
features = df[["Population", "Services_Used"]]

kmeans = KMeans(n_clusters=3)
df["Cluster"] = kmeans.fit_predict(features)

print("\nCluster Labels:\n", df["Cluster"])

# Step 6: Visualization

# Line Plot
[Link](df["Population"], df["Services_Used"])
[Link]("Population vs Services Used")
[Link]("Population")
[Link]("Services Used")
[Link]()

# Bar Chart
[Link]("Region")["Services_Used"].mean().plot(kind='bar')
[Link]("Average Services Used by Region")
[Link]()

# Histogram
[Link](df["Services_Used"])
[Link]("Distribution of Services Used")
[Link]()

Sample Input (CSV File: egov_data.csv)


Region,Population,Services_Used
Urban,10000,50
Rural,8000,30
Semi-Urban,9000,40
Urban,12000,60
Rural,7000,25

Sample Output
First 5 rows:
Region Population Services_Used
0 Urban 10000 50
1 Rural 8000 30
2 Semi-Urban 9000 40
3 Urban 12000 60
4 Rural 7000 25

Regression Coefficient: [0.005]


Intercept: 0.0
Cluster Labels:
0 1
1 0
2 2
3 1
4 0

(Graphs displayed: Line plot, Bar chart, Histogram)

Result
Thus, the E-Governance dataset was successfully loaded, cleaned, analyzed using linear regression
and clustering, and visualized using graphs.

Experiment 1: Data Visualization using


Matplotlib and Seaborn
Aim
To create a line chart using Matplotlib and a bar plot using Seaborn.

Algorithm
1. Start the program.
2. Import required libraries (Matplotlib, Seaborn).
3. Prepare sample data.
4. Plot a line chart using Matplotlib.
5. Plot a bar chart using Seaborn.
6. Display the plots.
7. Stop the program.

Program (Python)
import [Link] as plt
import seaborn as sns

# Sample Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
# Line Chart (Matplotlib)
[Link](x, y)
[Link]("Line Chart")
[Link]("X values")
[Link]("Y values")
[Link]()

# Bar Plot (Seaborn)


[Link](x=x, y=y)
[Link]("Bar Plot")
[Link]()

Sample Input
(No input required)

Sample Output
 Line chart showing trend of values
 Bar chart showing comparison of values

Result
Thus, line and bar charts were successfully created.

Experiment 2: Django Web Application


Aim
To create a Django project, implement authentication, connect database, perform CRUD operations,
and create an API.

Algorithm
1. Install Django and Django REST Framework.
2. Create a Django project and app.
3. Configure database (SQLite/MySQL).
4. Create models and migrate database.
5. Implement user registration and login.
6. Perform CRUD operations using models.
7. Create API endpoint using REST framework.
8. Run server and test application.

Program (Key Commands & Code)


Step 1: Create Project and App
django-admin startprojectmyproject
cd myproject
python [Link] startappmyapp

Step 2: Model ([Link])


from [Link] import models

class Service([Link]):
name = [Link](max_length=100)
description = [Link]()

Step 3: Migrate Database


python [Link] makemigrations
python [Link] migrate

Step 4: Views (CRUD)


from [Link] import render
from .models import Service

defcreate_service(request):
[Link](name="Test", description="Demo")

Step 5: Authentication
from [Link] import User
[Link].create_user(username="admin", password="1234")

Step 6: API (Django REST Framework)


from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Service

@api_view(['GET'])
defget_services(request):
services = list([Link]())
return Response(services)

Sample Input
 Username: admin
 Password: 1234

Sample Output
 User successfully registered and logged in
 API returns JSON data:

[
{"name": "Test", "description": "Demo"}
]

Result
Thus, a Django application with authentication, database, CRUD operations, and API was successfully
implemented.

Experiment 3: Flask Web Application


Aim
To create a basic web application using Flask framework.

Algorithm
1. Install Flask.
2. Create a Flask application.
3. Define routes.
4. Run server.
5. Display output in browser.
Program (Python)
from flask import Flask

app = Flask(__name__)

@[Link]('/')
def home():
return "Welcome to Flask Web App"

@[Link]('/about')
def about():
return "About Page"

if __name__ == '__main__':
[Link](debug=True)

Sample Input
(Open browser and visit URL)

[Link]

Sample Output
Welcome to Flask Web App

Result
Thus, a basic web application using Flask framework was successfully created and executed.

Mini Project: E-Governance Application


Aim
To develop a simple E-Governance web application with front-end forms, back-end authentication,
database models, data visualization, REST APIs, and deployment.

Algorithm
1. Start the project.
2. Design front-end using HTML/CSS forms for citizen registration and service requests.
3. Set up back-end using Flask/Django.
4. Implement user authentication (login/register).
5. Create database models for citizens and services.
6. Perform CRUD operations (Create, Read, Update, Delete).
7. Generate data visualizations using Matplotlib/Seaborn.
8. Create REST API endpoints for data access.
9. Run the application locally.
10. Test all functionalities.
11. Stop the program.

(i) Front-End: HTML Form


Program (HTML)
<!DOCTYPE html>
<html>
<head>
<title>Citizen Registration</title>
</head>
<body>
<h2>Register</h2>
<form method="POST" action="/register">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
Region: <input type="text" name="region"><br>
Service Required: <input type="text" name="service"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

(ii) Back-End (Flask Example)


Program (Python)
from flask import Flask, request, render_template
import sqlite3

app = Flask(__name__)

# Database connection
defconnect_db():
return [Link]("[Link]")

@[Link]('/')
def home():
return render_template("[Link]")

@[Link]('/register', methods=['POST'])
def register():
name = [Link]['name']
email = [Link]['email']
region = [Link]['region']
service = [Link]['service']

conn = connect_db()
cursor = [Link]()
[Link]("INSERT INTO citizens (name, email, region, service) VALUES
(?, ?, ?, ?)",
(name, email, region, service))
[Link]()
[Link]()

return "Registration Successful"

if __name__ == '__main__':
[Link](debug=True)

Database Model (SQLite)


CREATE TABLE citizens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT,
region TEXT,
service TEXT
);

(iii) Data Visualization


Program (Python)
import [Link] as plt
import sqlite3

conn = [Link]("[Link]")
data = [Link]("SELECT region, COUNT(*) FROM citizens GROUP BY
region").fetchall()

regions = [row[0] for row in data]


counts = [row[1] for row in data]

[Link](regions, counts)
[Link]("Services Used per Region")
[Link]("Region")
[Link]("Count")
[Link]()

(iv) API Development


Program (Flask API)
from flask import jsonify

@[Link]('/api/citizens', methods=['GET'])
defget_citizens():
conn = connect_db()
cursor = [Link]()
[Link]("SELECT * FROM citizens")
data = [Link]()
[Link]()

return jsonify(data)

(v) Deployment (Local Execution)


Steps
pip install flask matplotlib
python [Link]

Open browser:

[Link]

Sample Input
 Name: John
 Email: john@[Link]
 Region: Urban
 Service: Water Supply
Sample Output
Registration Successful

API Output:

[
[1, "John", "john@[Link]", "Urban", "Water Supply"]
]

Graph Output:

 Bar chart showing number of services per region

Result
Thus, the E-Governance application was successfully developed with front-end forms, back-end
processing, database integration, visualization, API creation, and deployment.

Experiment 1: Analyze Dataset for


Completeness and Consistency
Aim
To analyze a dataset for completeness (missing values) and consistency (data correctness).

Algorithm
1. Start the program.
2. Load dataset using Pandas.
3. Check missing values using isnull().
4. Check duplicates using duplicated().
5. Validate data types and ranges.
6. Display inconsistencies.
7. Stop the program.

Program (Python)
import pandas as pd

data = {
"Name": ["Alice", "Bob", None, "David"],
"Age": [25, 30, 30, -5]
}

df = [Link](data)

print("Missing Values:\n", [Link]())


print("\nDuplicates:\n", [Link]())
print("\nInvalid Ages:\n", df[df["Age"] < 0])

Sample Input
(No input required)

Sample Output
Missing Values:
Name Age
0 False False
1 False False
2 True False
3 False False

Duplicates:
0 False
1 False
2 False
3 False

Invalid Ages:
Name Age
3 David -5

Result
Thus, dataset completeness and consistency were analyzed successfully.

Experiment 2: IT Service Mapping &


Monitoring
Aim
To map IT services of a government portal and analyze uptime and logging metrics.

Algorithm
1. Identify system components (login, forms, database).
2. Simulate uptime logs.
3. Calculate uptime percentage.
4. Analyze logs for errors.
5. Display metrics.

Program (Python)
logs = ["UP", "UP", "DOWN", "UP", "UP"]

uptime = [Link]("UP") / len(logs) * 100


downtime = [Link]("DOWN")

print("Uptime %:", uptime)


print("Downtime Count:", downtime)

Sample Input
Logs: UP, UP, DOWN, UP, UP

Sample Output
Uptime %: 80.0
Downtime Count: 1

Result
Thus, uptime and logging metrics were successfully analyzed.

Experiment 3: Model Accuracy Check


Aim
To evaluate the accuracy of a simple model before deployment.

Algorithm
1. Import required libraries.
2. Define actual and predicted values.
3. Calculate accuracy score.
4. Display result.

Program (Python)
from [Link] import accuracy_score

y_true = [1, 0, 1, 1]
y_pred = [1, 0, 0, 1]

accuracy = accuracy_score(y_true, y_pred)


print("Accuracy:", accuracy)

Sample Input
(No input required)
Sample Output
Accuracy: 0.75

Result
Thus, the model accuracy was successfully evaluated.

Experiment 4: Gantt Chart for Project


Aim
To create a simple Gantt chart for portal development.

Algorithm
1. Define tasks and durations.
2. Use Matplotlib to plot bar chart.
3. Display Gantt chart.

Program (Python)
import [Link] as plt

tasks = ["Design", "Development", "Testing"]


duration = [3, 5, 2]

[Link](tasks, duration)
[Link]("Project Gantt Chart")
[Link]("Days")
[Link]("Tasks")
[Link]()

Sample Input
(No input required)
Sample Output
 Horizontal bar chart representing project timeline

Result
Thus, the Gantt chart was successfully created.

Experiment 5: Risk Evaluation in Dataset


Aim
To evaluate risks in a dataset based on predefined conditions.

Algorithm
1. Load dataset.
2. Define risk conditions (e.g., low usage).
3. Filter risky records.
4. Display results.

Program (Python)
import pandas as pd

data = {
"Region": ["Urban", "Rural", "Urban", "Rural"],
"Usage": [50, 10, 60, 5]
}

df = [Link](data)

risk = df[df["Usage"] < 20]


print("High Risk Areas:\n", risk)

Sample Input
(No input required)

Sample Output
High Risk Areas:
Region Usage
1 Rural 10
3 Rural 5

Result
Thus, risks in the dataset were successfully identified.

You might also like