Exam Prep

CBSE Class 12 Computer Science Important Questions 2026-27, Chapter Wise

Chapter-wise important questions for CBSE Class 12 Computer Science 2026-27. File handling, SQL, networking, stack, exception handling with answers.

This is a collection of the most important questions for the CBSE Class 12 Computer Science board exam (2026-27 session). These questions are based on previous year papers, sample papers, and NCERT textbook exercises.

Marks Distribution (2026-27)

Unit Topics Marks
1 Computational Thinking and Programming, 2 40
2 Computer Networks 10
3 Database Management 20
Total 70

Theory: 70 marks | Practical: 30 marks | Total: 100 marks


Chapter 1: Exception Handling (3-5 Marks)

Q1: What is exception handling? Name the keywords used in Python for exception handling.

Exception handling is a mechanism to handle runtime errors gracefully without crashing the program. Python uses four keywords:

  • try - Block of code that might cause an error
  • except - Block that handles the error
  • else - Executes if no exception occurs
  • finally - Always executes, whether exception occurs or not

Q2: What is the difference between syntax error and runtime error? Give examples.

Syntax error occurs when Python cannot understand the code. The program does not run at all.

print("Hello"   # SyntaxError: missing closing bracket

Runtime error occurs while the program is running. The code is syntactically correct but fails during execution.

a = 10 / 0      # ZeroDivisionError

Q3: Write the output of the following code:

try:
    num = int(input("Enter a number: "))   # User enters "abc"
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Invalid input!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("No error occurred")
finally:
    print("Program ended")

Answer (when user enters "abc"):

Invalid input!
Program ended

The else block does not execute because an exception occurred. The finally block always executes.

Q4: Write a Python program that handles both ValueError and ZeroDivisionError with appropriate messages.

try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))
    result = a / b
    print("Result:", result)
except ValueError:
    print("Error: Please enter integers only")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed")
finally:
    print("Thank you for using the program")

Chapter 2: File Handling (8-10 Marks)

Q1: What is the difference between read(), readline(), and readlines()?

Method Returns Description
read() String Reads the entire file as a single string
readline() String Reads one line at a time
readlines() List Reads all lines and returns a list of strings

Q2: Write a function to count the number of words "the" (case-insensitive) in a text file "article.txt".

def count_the():
    count = 0
    with open("article.txt", "r") as f:
        content = f.read()
        words = content.lower().split()
        for word in words:
            if word == "the":
                count += 1
    return count

print("Count of 'the':", count_the())

Q3: Write a function to read a binary file "employee.dat" containing records in the form [EmpID, Name, Salary] and display records where Salary is more than 50000.

import pickle

def display_high_salary():
    f = open("employee.dat", "rb")
    try:
        while True:
            record = pickle.load(f)
            if record[2] > 50000:
                print(f"ID: {record[0]}, Name: {record[1]}, Salary: {record[2]}")
    except EOFError:
        pass
    f.close()

display_high_salary()

Q4: What is the difference between write() and writelines()?

  • write(string) writes a single string to the file. It does not add a newline character automatically.
  • writelines(list) writes a list of strings to the file. It does not add newline characters between strings.
f = open("test.txt", "w")
f.write("Hello\n")                          # Single string
f.writelines(["Line 1\n", "Line 2\n"])     # List of strings
f.close()

Q5: Write a function to write student data into a CSV file "results.csv" and another function to read and display it.

import csv

def write_csv():
    with open("results.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["RollNo", "Name", "Marks"])
        writer.writerow([1, "Aman", 85])
        writer.writerow([2, "Priya", 92])

def read_csv():
    with open("results.csv", "r") as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)

write_csv()
read_csv()

Chapter 3: Stack (5-6 Marks)

Q1: Write a program to implement a stack using a list. Include Push, Pop, and Display operations.

stack = []

def push(item):
    stack.append(item)
    print(f"Pushed: {item}")

def pop():
    if stack:
        return stack.pop()
    else:
        print("Stack Underflow!")
        return None

def display():
    if stack:
        print("Stack (top to bottom):", stack[::-1])
    else:
        print("Stack is empty")

# Menu-driven program
while True:
    print("\n1. Push  2. Pop  3. Display  4. Exit")
    choice = int(input("Enter choice: "))
    if choice == 1:
        item = input("Enter item: ")
        push(item)
    elif choice == 2:
        val = pop()
        if val:
            print("Popped:", val)
    elif choice == 3:
        display()
    elif choice == 4:
        break

Q2: Write a function to push book titles onto a stack and display them.

def push_books():
    stack = []
    books = ["Python Basics", "Data Structures", "SQL Fundamentals"]
    for book in books:
        stack.append(book)
        print(f"Pushed: {book}")
    print("Stack:", stack)
    while stack:
        print("Popped:", stack.pop())

push_books()

Q3: What is stack overflow and stack underflow?

  • Stack Overflow occurs when you try to push an element onto a stack that is already full (in fixed-size stacks).
  • Stack Underflow occurs when you try to pop an element from an empty stack.

In Python, lists grow dynamically so overflow does not occur, but underflow can happen if you pop from an empty list.


Chapter 4: SQL (8-10 Marks)

Consider the table PRODUCT:

PID PName Price Qty Category
P01 Keyboard 800 50 Accessories
P02 Mouse 500 80 Accessories
P03 Monitor 12000 20 Display
P04 Printer 8000 15 Output
P05 Headphones 1500 60 Accessories

Q1: Write SQL queries for the following:

(a) Display all products with price more than 1000.

SELECT * FROM PRODUCT WHERE Price > 1000;

(b) Display product names and prices in descending order of price.

SELECT PName, Price FROM PRODUCT ORDER BY Price DESC;

(c) Display the total quantity of products in each category.

SELECT Category, SUM(Qty) FROM PRODUCT GROUP BY Category;

(d) Display categories having more than 2 products.

SELECT Category, COUNT(*) FROM PRODUCT GROUP BY Category HAVING COUNT(*) > 2;

Q2: What is the difference between WHERE and HAVING?

WHERE HAVING
Filters individual rows Filters groups
Used before GROUP BY Used after GROUP BY
Cannot use aggregate functions Can use aggregate functions
Works on any SELECT Works only with GROUP BY

Q3: Write the output:

SELECT COUNT(*), MAX(Price), AVG(Price) FROM PRODUCT WHERE Category = 'Accessories';
COUNT(*) | MAX(Price) | AVG(Price)
---------|------------|----------
3        | 1500       | 933.33

Q4: What is the difference between DELETE and DROP?

  • DELETE removes rows from a table. The table structure remains. It is a DML command.
  • DROP removes the entire table including its structure. It is a DDL command.

Q5: Write SQL to create the PRODUCT table.

CREATE TABLE PRODUCT (
    PID VARCHAR(5) PRIMARY KEY,
    PName VARCHAR(30) NOT NULL,
    Price DECIMAL(10,2),
    Qty INT,
    Category VARCHAR(20)
);

Chapter 5: Database Concepts (3-4 Marks)

Q1: What is a primary key? What are its properties?

A primary key is a column (or set of columns) that uniquely identifies each row in a table.

Properties:

  • Must contain unique values (no duplicates), Cannot contain NULL values, A table can have only one primary key, It automatically creates an index

Q2: What is the difference between candidate key and primary key?

  • Candidate key is any column that can uniquely identify rows. A table can have multiple candidate keys.
  • Primary key is the candidate key chosen by the database designer to uniquely identify rows. Only one primary key per table.

Q3: What is referential integrity? Explain with an example.

Referential integrity ensures that a foreign key value in one table must match an existing primary key value in the referenced table (or be NULL).

Example: If a STUDENT table has a ClassID column referencing the CLASS table, you cannot insert a ClassID in STUDENT that does not exist in CLASS.

Q4: Differentiate between DDL, DML, and DCL commands.

DDL DML DCL
Data Definition Language Data Manipulation Language Data Control Language
CREATE, ALTER, DROP SELECT, INSERT, UPDATE, DELETE GRANT, REVOKE
Defines table structure Modifies table data Controls access permissions

Chapter 6: Computer Networks (10 Marks)

Q1: What is the difference between a switch and a router?

Switch Router
Connects devices within a LAN Connects different networks
Works at Data Link Layer Works at Network Layer
Uses MAC addresses Uses IP addresses
Faster within a network Routes traffic between networks

Q2: What are the different types of network topologies? Draw any two.

  • Star topology - All devices connect to a central hub/switch
  • Bus topology - All devices connect to a single cable
  • Ring topology - Each device connects to two neighbors forming a ring
  • Mesh topology - Every device connects to every other device

Q3: Explain the following protocols: HTTP, FTP, SMTP, POP3, TCP/IP.

  • HTTP (Hypertext Transfer Protocol), Used to transfer web pages
  • FTP (File Transfer Protocol), Used to transfer files between computers
  • SMTP (Simple Mail Transfer Protocol), Used to send emails
  • POP3 (Post Office Protocol 3), Used to receive emails
  • TCP/IP (Transmission Control Protocol/Internet Protocol), Foundation protocol for all internet communication

Q4: A school has 4 buildings. Suggest the most suitable cable layout and placement of server.

This is a case-study question worth 5 marks. When answering:

  1. Identify the building with maximum computers as the server location
  2. Draw the cable layout connecting all buildings (usually star topology with one central building)
  3. Suggest repeaters if the cable distance exceeds 70 meters
  4. Recommend a switch/hub for each building
  5. Suggest a firewall for internet security

Q5: What is the difference between website and web page? What is a web browser?

  • A website is a collection of related web pages under a single domain name (e.g., google.com), A web page is a single document on the internet (e.g., google.com/about), A web browser is software used to access and display web pages (e.g., Chrome, Firefox)

Last-Minute Revision Checklist

  • Exception handling keywords: try, except, else, finally
  • File handling: read(), readline(), readlines(), write(), writelines()
  • Binary file: pickle.dump(), pickle.load(), EOFError handling
  • CSV file: csv.reader(), csv.writer(), newline=""
  • Stack: push (append), pop (pop), underflow check
  • SQL: SELECT, WHERE, GROUP BY, HAVING, ORDER BY, aggregate functions
  • DDL vs DML vs DCL commands
  • Primary key, foreign key, candidate key
  • Network topologies, protocols, devices
  • Python-MySQL: connect(), cursor(), execute(), fetchall(), commit()

Focus your revision on file handling and SQL. Together they carry approximately 20 marks out of 70 in the theory exam. Practice writing code by hand, as the board exam is pen-and-paper based.

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube