Current Affairs updated daily
KalviGavaniKalviGavani

CBSE Class 12 Informatics Practices NCERT Exercise Solutions

CBSE Class 12 Informatics Practices NCERT exercise solutions — Python (Pandas/Matplotlib), SQL, networking, cybersecurity with MCQs, short and long answer Q&A.

Updated 17 June 202610 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

CBSE Class 12 Informatics Practices — NCERT Exercise Solutions


Unit 1 — Python for Data Handling

Key Concepts — Pandas

TermDescription
Series1-D labelled array in Pandas
DataFrame2-D tabular data structure with rows and columns
read_csv()Read CSV file into DataFrame
head(n)First n rows (default 5)
tail(n)Last n rows
info()Summary of DataFrame (dtypes, null counts)
describe()Statistical summary (mean, std, min, max, quartiles)
groupby()Group data by column for aggregate operations
loc[]Label-based indexing
iloc[]Integer-based indexing

MCQs

1. Which Pandas function is used to read a CSV file? (a) open() (b) read_csv() (c) import_csv() (d) load_csv()

Answer(b) read_csv()

2. What does df.shape return? (a) Number of rows only (b) Number of columns only (c) Tuple of (rows, columns) (d) Total number of elements

Answer(c) Tuple of (rows, columns)

3. Which method removes rows with missing values? (a) dropna() (b) fillna() (c) drop() (d) remove_null()

Answer(a) dropna()

4. To select rows where salary > 50000 in DataFrame df: (a) df[df['salary'] > 50000] (b) df.select('salary > 50000') (c) df.filter(salary > 50000) (d) df.query > 50000

Answer(a) df[df['salary'] > 50000]

Short Answer Questions

Q1. Differentiate between Series and DataFrame in Pandas.
Answer
FeatureSeriesDataFrame
Dimensions1-D2-D
StructureSingle column with indexMultiple columns with row and column index
Creationpd.Series([1,2,3])pd.DataFrame({'A': [1,2], 'B': [3,4]})
AnalogySingle Excel columnComplete Excel sheet

Q2. Write Python code to: (a) Create a DataFrame from a dictionary (b) Display first 3 rows (c) Find mean of a column
import pandas as pd

# (a) Create DataFrame
data = {
    'Name': ['Asha', 'Ram', 'Priya', 'Raj'],
    'Marks': [85, 78, 92, 65],
    'Grade': ['A', 'B', 'A', 'C']
}
df = pd.DataFrame(data)

# (b) First 3 rows
print(df.head(3))

# (c) Mean of Marks column
print(df['Marks'].mean())

Q3. What is groupby() in Pandas? Give an example.
Answer

groupby() groups rows sharing a common value for aggregate operations (sum, mean, count, max, min).

import pandas as pd

df = pd.DataFrame({
    'Dept': ['IT', 'HR', 'IT', 'HR', 'IT'],
    'Salary': [60000, 45000, 70000, 50000, 65000]
})

# Average salary per department
result = df.groupby('Dept')['Salary'].mean()
print(result)
# Output:
# Dept
# HR    47500.0
# IT    65000.0

Unit 2 — Data Visualisation with Matplotlib

Key Concepts

Chart typeMatplotlib functionUse case
Line plotplt.plot()Trends over time
Bar chartplt.bar()Category comparison
Horizontal barplt.barh()Categories with long labels
Histogramplt.hist()Frequency distribution
Scatter plotplt.scatter()Correlation between two variables
Pie chartplt.pie()Parts of a whole (%)

Short Answer Questions

Q1. Write a Python program to plot a bar chart showing marks of 5 students.
import matplotlib.pyplot as plt

students = ['Asha', 'Ram', 'Priya', 'Raj', 'Nita']
marks = [85, 72, 90, 65, 78]

plt.bar(students, marks, color='steelblue')
plt.title('Student Marks')
plt.xlabel('Students')
plt.ylabel('Marks')
plt.ylim(0, 100)
plt.show()

Q2. What is a histogram? How is it different from a bar chart?
Answer
FeatureHistogramBar Chart
Data typeContinuous (numerical)Categorical (discrete)
BarsTouch each other (no gap)Have gaps between bars
X-axisNumber ranges (bins)Category names
PurposeShows frequency distributionCompares categories
import matplotlib.pyplot as plt

scores = [45, 52, 60, 65, 68, 70, 75, 78, 80, 85, 90, 92]
plt.hist(scores, bins=5, color='orange', edgecolor='black')
plt.title('Score Distribution')
plt.xlabel('Score Range')
plt.ylabel('Frequency')
plt.show()

Unit 3 — SQL and Databases

Key Concepts

TermDefinition
DDLData Definition Language: CREATE, ALTER, DROP, TRUNCATE
DMLData Manipulation Language: INSERT, UPDATE, DELETE, SELECT
Primary KeyUniquely identifies each row; cannot be NULL
Foreign KeyReferences primary key of another table
NULLAbsence of a value (not zero, not empty string)
ConstraintRule enforced on data (NOT NULL, UNIQUE, CHECK, DEFAULT)

MCQs

1. Which SQL command removes a table's structure permanently? (a) TRUNCATE (b) DELETE (c) DROP (d) REMOVE

Answer(c) DROP

2. Which aggregate function returns the number of rows? (a) SUM() (b) COUNT() (c) AVG() (d) TOTAL()

Answer(b) COUNT()

3. The HAVING clause is used with: (a) WHERE (b) GROUP BY (c) ORDER BY (d) JOIN

Answer(b) GROUP BY

Short Answer Questions

Q1. Write SQL to create a table Student with columns: RollNo (int, PK), Name (varchar 30, not null), Marks (decimal 5,2), Grade (char 1).
CREATE TABLE Student (
    RollNo INT PRIMARY KEY,
    Name VARCHAR(30) NOT NULL,
    Marks DECIMAL(5,2),
    Grade CHAR(1)
);

Q2. Write SQL queries for the following using the Student table:
Answer
  • (a) Add a new student: 101, 'Asha', 92.5, 'A'
  • (b) Display all students scoring above 75
  • (c) Count students in each grade
  • (d) Update Asha's marks to 95
-- (a) Insert
INSERT INTO Student VALUES (101, 'Asha', 92.5, 'A');

-- (b) Filter
SELECT * FROM Student WHERE Marks > 75;

-- (c) Group and count
SELECT Grade, COUNT(*) AS Total
FROM Student
GROUP BY Grade;

-- (d) Update
UPDATE Student SET Marks = 95 WHERE Name = 'Asha';

Q3. Explain the difference between WHERE and HAVING with an example.
Answer
  • WHERE filters individual rows before grouping.
  • HAVING filters groups after GROUP BY.
-- WHERE: filter individual rows
SELECT * FROM Student WHERE Marks > 80;

-- HAVING: filter groups
SELECT Grade, AVG(Marks) AS AvgMarks
FROM Student
GROUP BY Grade
HAVING AVG(Marks) > 75;

Q4. What is a JOIN? Write SQL for INNER JOIN between two tables.
Answer

JOIN combines rows from two tables based on a related column.

-- Tables: Student(RollNo, Name, CourseID) and Course(CourseID, CourseName)

SELECT Student.Name, Course.CourseName
FROM Student
INNER JOIN Course ON Student.CourseID = Course.CourseID;

INNER JOIN returns only rows where there is a match in both tables.


Unit 4 — Computer Networks

Key Concepts

TermDefinition
LANLocal Area Network — limited geographic area
WANWide Area Network — large geographic area (internet)
MANMetropolitan Area Network — city scale
IP addressUnique numerical address for each device on a network
DNSDomain Name System — translates domain names to IP addresses
HTTP/HTTPSProtocol for web communication; HTTPS is encrypted
FTPFile Transfer Protocol — transferring files
SMTPSimple Mail Transfer Protocol — sending email
POP3/IMAPReceiving email protocols
RouterConnects different networks; routes packets
SwitchConnects devices within a LAN; smarter than hub

MCQs

1. Which device connects a LAN to the internet? (a) Hub (b) Switch (c) Router (d) Repeater

Answer(c) Router

2. What does DNS stand for? (a) Data Network System (b) Domain Name System (c) Digital Network Service (d) Dynamic Node Service

Answer(b) Domain Name System

3. Which protocol is used for secure web browsing? (a) HTTP (b) FTP (c) HTTPS (d) SMTP

Answer(c) HTTPS

Short Answer Questions

Q1. Differentiate between hub, switch, and router.
Answer
DeviceFunctionLevel
HubBroadcasts to ALL devices; creates collision domainPhysical layer
SwitchSends data ONLY to intended device using MAC addressData link layer
RouterConnects different networks; uses IP addresses; routes packetsNetwork layer

Q2. What is an IP address? Differentiate between IPv4 and IPv6.
Answer

An IP address is a unique numerical identifier assigned to each device on a network.

FeatureIPv4IPv6
Size32-bit128-bit
FormatDotted decimal: 192.168.1.1Hexadecimal: 2001:0db8::1
Addresses~4.3 billion3.4 × 10³⁸ (virtually unlimited)
ProblemAddress exhaustionSolves IPv4 shortage

Unit 5 — Cybersecurity

Key Concepts

ThreatDescription
MalwareMalicious software: virus, worm, Trojan, ransomware, spyware
PhishingFraudulent email/website pretending to be legitimate to steal credentials
SQL InjectionInserting malicious SQL into web forms to access/corrupt databases
DoS attackDenial of Service — flooding server to make it unavailable
KeyloggerSoftware that records keystrokes to steal passwords
FirewallSoftware/hardware that monitors and controls network traffic
EncryptionConverting data into coded form to prevent unauthorised access

Short Answer Questions

Q1. What is phishing? How can you protect yourself?
Answer

Phishing is a cyberattack where an attacker impersonates a legitimate organisation (bank, government) via fake emails, websites, or SMS to trick users into revealing passwords, credit card numbers, or personal data.

Protection:

  • Check sender email address carefully (phishing emails have slight misspellings).
  • Never click links in unsolicited emails — go directly to the website.
  • Look for HTTPS and padlock before entering passwords.
  • Enable two-factor authentication (2FA).
  • Keep security software updated.

Q2. What are the safe practices for internet use?
Answer
  • Use strong passwords (8+ characters, mix of letters/numbers/symbols).
  • Never share passwords with anyone.
  • Enable 2FA on all accounts.
  • Keep software and OS updated.
  • Avoid public Wi-Fi for banking; use VPN if necessary.
  • Don't share personal information on social media.
  • Regularly back up data (ransomware protection).
  • Be skeptical of "too good to be true" online offers.

Worked Examples

Example 1 — Pandas operations on student data

import pandas as pd

df = pd.read_csv('students.csv')

# Find top scorer
print(df[df['Marks'] == df['Marks'].max()])

# Average marks by class
print(df.groupby('Class')['Marks'].mean())

# Students who passed (Marks >= 35)
passed = df[df['Marks'] >= 35]
print(f"Pass percentage: {len(passed)/len(df)*100:.1f}%")

Example 2 — SQL with aggregate functions

-- Highest marks per grade
SELECT Grade, MAX(Marks) AS Highest, MIN(Marks) AS Lowest, AVG(Marks) AS Average
FROM Student
GROUP BY Grade
ORDER BY Average DESC;

-- Students above class average
SELECT Name, Marks
FROM Student
WHERE Marks > (SELECT AVG(Marks) FROM Student);

Exam Tips

  • Pandas questions always ask: create DataFrame, filter, groupby, or merge.
  • SQL: GROUP BY + HAVING is a very common question — remember HAVING comes after GROUP BY.
  • Networking: know which device works at which layer (hub=physical, switch=data link, router=network).
  • Cybersecurity: always answer with examples — phishing example, ransomware example.
  • Chart type selection: trend over time → line; categories → bar; distribution → histogram; relationship → scatter.

Frequently Asked Questions

Python (Pandas, Matplotlib), SQL (DDL, DML, aggregate functions, joins), computer networks (protocols, topologies), cybersecurity (threats, safe practices).