Class 12 Advanced Python & AI Practical Programs
1. Student Marks Analysis Tool
Aim: Analyze student marks from CSV, compute statistics, plot charts, and
save summary. Tools Required: Python IDLE, Pandas, NumPy, Matplotlib,
CSV file ([Link]) Procedure: 1. Read CSV file containing student
marks. 2. Compute mean, median, mode, standard deviation. 3. Plot bar
chart for marks. 4. Save summary statistics to a new CSV file. Program:
import pandas as pd
import numpy as np
import [Link] as plt
from scipy import stats
df = pd.read_csv("[Link]")
mean_marks = df['Marks'].mean()
median_marks = df['Marks'].median()
mode_marks = [Link](df['Marks'])[0][0]
std_marks = df['Marks'].std()
print(f"Mean: {mean_marks}, Median: {median_marks}, Mode:
{mode_marks}, Std: {std_marks}")
[Link](df['Name'], df['Marks'])
[Link]("Students")
[Link]("Marks")
[Link]("Student Marks")
[Link]()
summary = [Link]({'Mean':[mean_marks],'Median':
[median_marks],'Mode':[mode_marks],'Std':[std_marks]})
summary.to_csv("[Link]", index=False)
Sample Output: Mean: 85.0, Median: 85.0, Mode: 88, Std: 3.5 Bar chart
displayed. [Link] created. Result: Successfully analyzed marks,
plotted chart, and saved summary.
2. Library Management System (Simplified)
Aim: Manage book records: add, delete, search, and update. Tools
Required: Python IDLE, CSV file ([Link]) Program:
import pandas as pd
try:
df = pd.read_csv("[Link]")
except:
df = [Link](columns=["ID","Title","Author"])
def add_book():
ID = int(input("Book ID: "))
title = input("Title: ")
author = input("Author: ")
global df
df = [Link]({"ID":ID,"Title":title,"Author":author},
ignore_index=True)
df.to_csv("[Link]", index=False)
print("Book added.")
def search_book():
title = input("Enter book title to search: ")
res = df[df['Title'].[Link](title, case=False)]
print(res)
while True:
print("[Link] Book [Link] Book [Link]")
ch = input("Choice: ")
if ch=='1': add_book()
elif ch=='2': search_book()
elif ch=='3': break
Result: Can add/search books dynamically with persistent storage.
3. Weather Data Analysis
Aim: Analyze temperature and rainfall trends. Tools Required: Python
IDLE, Pandas, Matplotlib, CSV file ([Link]) Program:
import pandas as pd
import [Link] as plt
df = pd.read_csv("[Link]")
print("Average Temp:", df['Temperature'].mean())
print("Total Rainfall:", df['Rainfall'].sum())
[Link](df['Day'], df['Temperature'], marker='o')
[Link]("Day")
[Link]("Temperature")
[Link]("Temperature Trend")
[Link]()
Result: Successfully analyzed weather data and plotted temperature trends.
4. Email Spam Detection System
Aim: Classify emails as spam or not using Naive Bayes. Tools Required:
Python IDLE, scikit-learn Program:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
emails = ["win cash now", "meeting at 10", "free lottery", "project
submission"]
labels = [1,0,1,0]
cv = CountVectorizer()
X = cv.fit_transform(emails)
model = MultinomialNB()
[Link](X, labels)
test = ["win free money"]
print("Prediction (1=spam, 0=not spam):",
[Link]([Link](test))[0])
Result: Successfully classified email as spam/not spam.
5. Sales Prediction Using Linear Regression
Aim: Predict future sales based on advertisement spend. Tools Required:
Python IDLE, Pandas, scikit-learn, Matplotlib Program:
import pandas as pd
from sklearn.linear_model import LinearRegression
import [Link] as plt
data = {'AdSpend':[10,20,30,40,50],'Sales':[25,45,65,80,95]}
df = [Link](data)
X = df[['AdSpend']]
y = df['Sales']
model = LinearRegression()
[Link](X, y)
spend = float(input("Enter Ad Spend: "))
pred = [Link]([[spend]])
print("Predicted Sales:", pred[0])
[Link](X, y)
[Link](X, [Link](X), color='red')
[Link]("Ad Spend")
[Link]("Sales")
[Link]()
Result: Predicted sales and plotted regression line successfully.
6. Student Performance Dashboard
Program:
import pandas as pd
import [Link] as plt
marks_df = pd.read_csv("[Link]")
attendance_df = pd.read_csv("[Link]")
df = [Link](marks_df, attendance_df, on="RollNo")
df['Total'] = df[['Math','Science','English']].sum(axis=1)
df['Average'] = df[['Math','Science','English']].mean(axis=1)
print(df)
[Link](df['Name'], df['Average'])
[Link]("Students")
[Link]("Average Marks")
[Link]("Student Performance Dashboard")
[Link]()
df.to_csv("student_dashboard.csv", index=False)
Result: Dashboard created with charts and CSV summary.
7. Mini Chatbot with FAQ Database
Program:
import pandas as pd
faq_df = pd.read_csv("[Link]")
def chatbot():
print("Hi! Ask me a question. Type 'bye' to exit.")
while True:
user_input = input("You: ").lower()
if user_input == 'bye':
print("Bot: Goodbye!")
break
response_found = False
for index, row in faq_df.iterrows():
if row['Question'].lower() in user_input:
print("Bot:", row['Answer'])
response_found = True
break
if not response_found:
print("Bot: Sorry, I don't know the answer.")
chatbot()
Result: Chatbot interacts based on CSV FAQ database.
8. Emotion Detection from Text
Program:
positive_words = ['happy', 'good', 'excited', 'joy']
negative_words = ['sad', 'angry', 'upset', 'bad']
def detect_emotion(text):
text = [Link]()
if any(word in text for word in positive_words):
return "Positive 😊"
elif any(word in text for word in negative_words):
return "Negative 😢"
else:
return "Neutral 😐"
while True:
sentence = input("Enter text (type 'exit' to quit): ")
if [Link]() == 'exit':
break
print("Detected Emotion:", detect_emotion(sentence))
Result: Successfully detects emotions from text.
9. Bank Account Management System
Program:
import pandas as pd
try:
df = pd.read_csv("[Link]")
except:
df = [Link](columns=["AccountNo", "Name", "Balance"])
def create_account():
acc = int(input("Account No: "))
name = input("Name: ")
balance = float(input("Initial Balance: "))
global df
df = [Link]({"AccountNo":acc, "Name":name, "Balance":balance},
ignore_index=True)
df.to_csv("[Link]", index=False)
print("Account created successfully.")
def deposit():
acc = int(input("Account No: "))
amount = float(input("Deposit Amount: "))
[Link][df['AccountNo']==acc, 'Balance'] += amount
df.to_csv("[Link]", index=False)
print("Deposit successful.")
def withdraw():
acc = int(input("Account No: "))
amount = float(input("Withdrawal Amount: "))
if [Link][df['AccountNo']==acc, 'Balance'].values[0] >= amount:
[Link][df['AccountNo']==acc, 'Balance'] -= amount
df.to_csv("[Link]", index=False)
print("Withdrawal successful.")
else:
print("Insufficient balance!")
def check_balance():
acc = int(input("Account No: "))
print("Balance:", [Link][df['AccountNo']==acc,
'Balance'].values[0])
while True:
print("[Link] Account [Link] [Link] [Link] Balance
[Link]")
choice = input("Choice: ")
if choice=='1': create_account()
elif choice=='2': deposit()
elif choice=='3': withdraw()
elif choice=='4': check_balance()
elif choice=='5': break
Result: Simulates bank operations successfully with persistent storage.
10. AI Prediction Mini-Project (Logistic Regression for
Pass/Fail)
Program:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score
data = {'Math':[35,50,70,90,40],'Science':[30,45,65,85,38],'English':
[40,55,75,95,42],'Result':[0,0,1,1,0]}
df = [Link](data)
X = df[['Math','Science','English']]
y = df['Result']
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=1)
model = LogisticRegression()
[Link](X_train, y_train)
marks = [[60, 70, 65]]
prediction = [Link](marks)
print("Prediction (1=Pass, 0=Fail):", prediction[0])
y_pred = [Link](X_test)
print("Accuracy on test data:", accuracy_score(y_test, y_pred))
Result: Successfully predicts pass/fail and computes model accuracy.