Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views6 pages

Class12 IP Practical File

The document contains practical solutions for Class 12 Informatics Practices using Python and SQL. It includes various Python functions for data manipulation and visualization with Pandas and Matplotlib, as well as SQL commands for managing student data in a database. The practical file serves as a comprehensive guide for students to learn and apply programming concepts in both Python and SQL.

Uploaded by

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

Class12 IP Practical File

The document contains practical solutions for Class 12 Informatics Practices using Python and SQL. It includes various Python functions for data manipulation and visualization with Pandas and Matplotlib, as well as SQL commands for managing student data in a database. The practical file serves as a comprehensive guide for students to learn and apply programming concepts in both Python and SQL.

Uploaded by

Preeti Saini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

==========================

Class 12 IP Practical File


==========================

Author: ChatGPT

---------------------------------
SECTION A: PYTHON SOLUTIONS
---------------------------------

"""
Class 12 Informatics Practices — Practical Solutions (Python + Pandas + NumPy +
Matplotlib)
Author: ChatGPT
Python 3.x
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# ---------- 1) Create a pandas Series from a dictionary of values and a Nd array


----------
def series_from_dict_and_ndarray():
d = {"a": 10, "b": 20, "c": 30}
s_dict = pd.Series(d, name="from_dict")
arr = np.array([100, 200, 300, 400])
s_arr = pd.Series(arr, index=list("wxyz"), name="from_ndarray")
return s_dict, s_arr

# ---------- 2) Create a Series using list ----------


def series_from_list():
data = [5, 9, 2, 7, 1]
s = pd.Series(data, index=list("abcde"), name="from_list")
return s

# ---------- 3) Creating a Series: Empty, Scalar and NumPy array ----------


def series_empty_scalar_numpy():
s_empty = pd.Series(dtype="float64", name="empty_series")
s_scalar = pd.Series(7, index=list("abcd"), name="scalar_series")
s_numpy = pd.Series(np.arange(1, 6), name="numpy_series")
return s_empty, s_scalar, s_numpy

# ---------- 4) Quarterly sales DataFrame and total expenditure per category


----------
def quarterly_sales_groupby():
df = pd.DataFrame({
"Category": ["Grocery", "Grocery", "Electronics", "Electronics",
"Stationery", "Grocery"],
"Item": ["Rice", "Pulses", "Headphones", "Mouse", "Pen", "Oil"],
"Expenditure": [1200, 800, 2500, 900, 300, 700],
"Quarter": ["Q1", "Q1", "Q2", "Q3", "Q4", "Q2"]
})
total_by_cat = df.groupby("Category", as_index=False)
["Expenditure"].sum().rename(columns={"Expenditure": "TotalExpenditure"})
return df, total_by_cat

# ---------- 5) Exam result DataFrame, show index/columns/dtypes/dimensions


----------
def exam_result_info():
exam_df = pd.DataFrame({
"RollNo": [1, 2, 3, 4],
"Name": ["Asha", "Brij", "Charu", "Deep"],
"Maths": [88, 76, 93, 67],
"Physics": [81, 69, 85, 72],
"Chemistry": [90, 74, 84, 70]
}).set_index("RollNo")
info = {
"row_labels": exam_df.index.tolist(),
"column_labels": exam_df.columns.tolist(),
"dtypes": exam_df.dtypes.astype(str).to_dict(),
"dimensions": exam_df.shape
}
return exam_df, info

# ---------- 6) Filter out duplicate rows ----------


def filter_duplicate_rows():
df = pd.DataFrame({
"Name": ["A", "B", "A", "C", "B"],
"Marks": [90, 85, 90, 78, 85]
})
unique_df = df.drop_duplicates()
return df, unique_df

# ---------- 7) Importing/Exporting CSV ----------


def import_export_csv(path="/mnt/data/sample.csv"):
df = pd.DataFrame({"id":[1,2,3], "name":["Riya","Ishan","Tara"], "score":
[91,85,88]})
df.to_csv(path, index=False)
loaded = pd.read_csv(path)
return df, loaded

# ---------- 8) Iterate over DataFrame of names/marks and add grade column


----------
def add_grades():
df = pd.DataFrame({
"Name":["Asha","Brij","Charu","Deep","Esha"],
"Marks":[95, 81, 67, 54, 39]
})
def grade(m):
if m >= 90: return "A+"
if m >= 80: return "A"
if m >= 70: return "B"
if m >= 60: return "C"
if m >= 50: return "D"
return "F"
df["Grade"] = df["Marks"].apply(grade)
return df

# ---------- 9) School result analysis: subjectwise/classwise ----------


def school_result_analysis():
df = pd.DataFrame({
"Class":["X","X","X","XI","XI","XI"],
"Student":["Asha","Brij","Charu","Deep","Esha","Firoz"],
"Maths":[88, 72, 91, 67, 83, 75],
"Science":[90, 69, 86, 70, 88, 78],
"English":[85, 74, 92, 73, 81, 80]
})
# Subject-wise mean
subjectwise_mean =
df[["Maths","Science","English"]].mean().to_frame("Average").T
# Class-wise average per subject
classwise = df.groupby("Class")[["Maths","Science","English"]].mean()
toppers =
df.assign(Total=df[["Maths","Science","English"]].sum(axis=1)).nlargest(3, "Total")
[["Student","Class","Total"]]
return df, subjectwise_mean, classwise, toppers

# ---------- 10) Create DataFrame and plot chart with title and legend ----------
def analysis_plot_example(show=False):
df = pd.DataFrame({
"Month":["Jan","Feb","Mar","Apr","May"],
"Sales_A":[120, 150, 130, 160, 180],
"Sales_B":[100, 140, 120, 155, 175]
})
if show:
plt.figure()
plt.plot(df["Month"], df["Sales_A"], label="Product A")
plt.plot(df["Month"], df["Sales_B"], label="Product B")
plt.title("Monthly Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales (Units)")
plt.legend()
plt.tight_layout()
plt.savefig("/mnt/data/monthly_sales_line.png")
return df

# ---------- 11) Simple line chart: growth of a plant over 5 days ----------
def plant_growth_chart(show=False):
days = [1,2,3,4,5]
height_cm = [2, 3.5, 5, 7.2, 9]
if show:
plt.figure()
plt.plot(days, height_cm, marker="o")
plt.title("Plant Growth Over 5 Days")
plt.xlabel("Day")
plt.ylabel("Height (cm)")
plt.grid(True)
plt.tight_layout()
plt.savefig("/mnt/data/plant_growth.png")
return days, height_cm

# ---------- 12) Bar chart: marks in 5 subjects ----------


def bar_chart_marks(show=False):
subjects = ["Maths","Science","English","Hindi","CS"]
marks = [88, 92, 81, 76, 95]
if show:
plt.figure()
plt.bar(subjects, marks)
plt.title("Marks in 5 Subjects")
plt.xlabel("Subject")
plt.ylabel("Marks")
plt.tight_layout()
plt.savefig("/mnt/data/marks_bar.png")
return subjects, marks

# ---------- 13) Horizontal bar chart: students in different streams ----------


def hbar_streams(show=False):
streams = ["Science","Commerce","Arts"]
counts = [120, 85, 60]
if show:
plt.figure()
plt.barh(streams, counts)
plt.title("Students per Stream")
plt.xlabel("Number of Students")
plt.tight_layout()
plt.savefig("/mnt/data/streams_hbar.png")
return streams, counts

# ---------- 14) Pie chart: percentage of time spent by a student in a day


----------
def pie_time_spent(show=False):
activities = ["Sleep","School","Study","Play","Other"]
hours = [8, 6, 3, 3, 4]
if show:
plt.figure()
plt.pie(hours, labels=activities, autopct="%1.1f%%", startangle=90)
plt.title("Daily Time Distribution")
plt.axis("equal")
plt.tight_layout()
plt.savefig("/mnt/data/time_pie.png")
return activities, hours

# ---------- 15) Bar chart for population of five cities using custom colors
----------
def bar_population_custom_colors(show=False):
cities = ["Delhi","Mumbai","Kolkata","Chennai","Bengaluru"]
population = [19, 20, 14, 11, 12] # in millions (example)
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"]
if show:
plt.figure()
plt.bar(cities, population, color=colors)
plt.title("Population of Five Cities")
plt.xlabel("City")
plt.ylabel("Population (Millions)")
plt.tight_layout()
plt.savefig("/mnt/data/population_custom_colors.png")
return cities, population

# ---------- 16) Pie chart favourite fruits with explode and shadow ----------
def pie_favourite_fruits(show=False):
fruits = ["Mango","Apple","Banana","Grapes"]
votes = [50, 30, 15, 5]
explode = [0.1, 0, 0, 0]
if show:
plt.figure()
plt.pie(votes, labels=fruits, explode=explode, shadow=True, autopct="%1.0f%
%")
plt.title("Favourite Fruits")
plt.axis("equal")
plt.tight_layout()
plt.savefig("/mnt/data/fruits_pie.png")
return fruits, votes

# ---------- 17) Concatenating two 2D arrays using single array ----------


def concatenate_two_2d_arrays():
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
concatenated = np.concatenate((a, b), axis=0) # vertical
return a, b, concatenated

# ---------- 18) Sort the data in DataFrame ----------


def sort_dataframe():
df = pd.DataFrame({
"Name":["Isha","Aman","Neel","Bela"],
"Marks":[85, 92, 78, 88]
})
sorted_by_name = df.sort_values(by="Name")
sorted_by_marks_desc = df.sort_values(by="Marks", ascending=False)
return df, sorted_by_name, sorted_by_marks_desc

# ---------- 19) Write in csv 'stud.csv' and display the content ----------
def write_and_read_stud_csv(path="/mnt/data/stud.csv"):
stud = pd.DataFrame({
"RollNo":[101,102,103],
"Name":["Anil","Beena","Chetan"],
"Marks":[86,91,77]
})
stud.to_csv(path, index=False)
read_back = pd.read_csv(path)
return stud, read_back

# ---------- 20) Binary operations on DataFrames ----------


def binary_operations_on_dataframes():
df1 = pd.DataFrame({"A":[1,2,3], "B":[4,5,6]})
df2 = pd.DataFrame({"A":[10,20,30], "B":[40,50,60]})
add = df1.add(df2, fill_value=0)
sub = df2.sub(df1, fill_value=0)
mul = df1.mul(df2, fill_value=1)
return df1, df2, add, sub, mul

if __name__ == "__main__":
# Run a few demonstrations and save charts
_, _ = analysis_plot_example(show=True)
_ = plant_growth_chart(show=True)
_ = bar_chart_marks(show=True)
_ = hbar_streams(show=True)
_ = pie_time_spent(show=True)
_ = bar_population_custom_colors(show=True)
_ = pie_favourite_fruits(show=True)

---------------------------------
SECTION B: SQL SOLUTIONS
---------------------------------

-- Class 12 IP — SQL Solutions

-- 1) Create a student table with id, name, marks (id as PRIMARY KEY)
CREATE TABLE student (
student_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
marks INT CHECK (marks >= 0 AND marks <= 100)
);
-- 2) Insert the details of a new student
INSERT INTO student (student_id, name, marks) VALUES (1, 'Asha', 92);

-- 3) Delete the details of a student


DELETE FROM student WHERE student_id = 1;

-- 4) Select students with marks more than 80


SELECT student_id, name, marks FROM student WHERE marks > 80;

-- 5) Find min, max, sum, average of marks


SELECT MIN(marks) AS min_marks, MAX(marks) AS max_marks,
SUM(marks) AS total_marks, AVG(marks) AS avg_marks
FROM student;

-- 6) Total number of customers from each country (customer_id, customer_name,


country)
-- Table: customers(customer_id INT, customer_name VARCHAR(50), country
VARCHAR(50))
SELECT country, COUNT(*) AS total_customers
FROM customers
GROUP BY country;

-- 7) Order (student_id, marks) table in descending order of marks


SELECT student_id, marks FROM student ORDER BY marks DESC;

-- 8) Display all records of student table


SELECT * FROM student;

-- 9) String functions (examples)


SELECT UPPER(name) AS upper_name, LOWER(name) AS lower_name,
LENGTH(name) AS name_length,
SUBSTRING(name, 1, 3) AS first_three,
CONCAT(name, ' - Grade A') AS concat_example,
TRIM(' hello ') AS trimmed;

-- 10) Date and Time functions (examples; MySQL/MariaDB syntax)


SELECT CURDATE() AS today, NOW() AS current_datetime,
YEAR(NOW()) AS year_now, MONTH(NOW()) AS month_now, DAY(NOW()) AS day_now,
DATEDIFF('2025-12-31', CURDATE()) AS days_until_2025_end;

You might also like