Class 12 Computer Science Board Question Paper 2024 with Answer Key

Computer Science Board Question Paper 2024 with solution

General Instructions:

(i) Please check this question paper contains 35 questions.

(ii) The paper is divided into 5 Sections – A, B, C, D and E.

(iii) Section A, consists of 18 questions (1 to 18). Each question carries 1 mark.

(iv) Section B, consists of 7 questions (19 to 25). Each question carries 2 marks.

(v) Section C, consists of 5 questions (26 to 30). Each question carries 3 marks.

(vi) Section D, consists of 2 questions (31 to 32). Each question carries 4 marks.

(vii) Section E, consists of 3 questions (33 to 35). Each question carries 5 marks.

(viii) All programming questions are to be answered using Python Language only.

Class 12 Computer Science Board Question Paper 2024

SECTION-A

State True or False:

1. While defining a function in Python, the positional parameters in the function header must always be written after the default parameters.

Answer: False

 

2. The SELECT statement when combined with ________  clause, returns  records without repetition.

(a) DISTINCT

(b) DESCRIBE

(c) UNIQUE

(d) NULL

Answer:(a) DISTINCT

 

3. What will be the output of the following statement:

print (16*5/4*2/5-8)

(a) -3.33

(b) 6.0

(c) 0.0

(d) -13.33

Answer:(b) 6.0

 

4. What possible output from the given options is expected to be displayed when the following Python code is executed?

import random

Signal = [‘RED’, ‘YELLOW’, ‘GREEN’]

for K in range(2, 0, 1):

          R= random.randrange (K)

           print (Signal [R], end = ‘#’)

(a) YELLOW # RED #

(b) RED #GREEN #

(c) GREEN #RED #

(d) YELLOW # GREEN #

Answer:(b) RED #GREEN #

 

5. In SQL, the aggregate function which will display the cardinality of the table is ________

(a) sum()

(b) count(*)

(c) avg ()

(d) sum(*)

Answer:(b) count(*)

 

6. Which protocol out of the following is used to send and receive emails over a computer network?

(a) PPP

(b) HTTP

(c) FTP

(d) SMTP

Answer:(d) SMTP

 

7. Identify the invalid Python statement from the following:

(a) d= dict ( )

(b) e ={ }

(c) f =[ ]

(d) g=dict{ }

Answer:(d) g=dict{ }

 

8. Consider the statements given below and then choose the correct output from the given options:

myStr=”MISSISSIPPI”

print(myStr[:4]+”#”+myStr [ – 5 :])

(a) MISSI#SIPPI

(b) MISS#SIPPI

(c) MISS#IPPIS

(d) MISSI#IPPIS

 

Answer:(b) MISS#SIPPI

 

9. Identify the statement from the following which will raise an error:

(a) print (” A “*3)

(b) print (5 * 3)

(c) print (” 15 “+3)

(d) print(“15” + “13”)

Answer:(c) print (” 15 “+3)

 

10. Select the correct output of the following code:

event=”G20 Presidency@2023″

L=event.split(‘  ‘)

print ( L [::-2])

(a) ‘G20’

(b) [‘Presidency@2023’]

(c) [‘G20’ ]

(d) ‘Presidency@2023’

Answer:(b) [‘Presidency@2023’]

 

11. Which of the following options is the correct unit of measurement for network bandwidth?

(a) KB

(b) Bit

(c) Hz

(d) Km

Answer:(c) Hz

 

12. Observe the given Python code carefully:

a=20

def convert(a):

         b=20

         a=a+b

convert (10)

print(a)

Select the correct output from the given options:

(a) 10

(b) 20

(c) 30

(d) Error

Answer:(b) 20

 

13. State whether the following statement is True or False:

While handling exceptions in Python, name of the exception has to be compulsorily added with except clause.

Answer: False

 

14. Which of the following is not a DDL command in SQL?

(a) DROP

(b) CREATE

(c) UPDATE

(d) ALTER

Answer:(c) UPDATE

 

15. Fill in the blank:

_____is a set of rules that needs to be followed by the communicating parties in order to have a successful and reliable data communication over a network.

Answer:Protocol

 

16. Consider the following Python statement:

F=open(‘CONTENT.TXT’)

Which of the following is an invalid statement in Python?

(a) F.seek (1,0)

(b) F.seek (0,1)

(c) F.seek (0,-1)

(d) F.seek (0,2)

Answer:(b) F.seek (0,1)

 

Q. 17 and 18 are ASSERTION (A) and REASONING (R) based questions. Mark the correct choice as

(a) Both (A) and (R) are true and (R) is the correct explanation for (A).

(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).

(c) (A) is true but (R) is false.

(d) (A) is false but (R) is true.

 

17. Assertion (A): CSV file is a human readable text file where each line has a number of fields, separated by comma or some other delimiter.

Reason (R) : writerow() method is used to write a single row in a CSV file.

Answer:(a) Both (A) and (R) are true and (R) is the correct explanation for (A).

 

18. Assertion (A): The expression “HELLO”.sort() in Python will give an error.

Reason (R) : sort() does not exist as a method/function for strings in Python.

Answer: (b) Both (A) and (R) are true and (R) is not the correct explanation for (A).

Class 12 Computer Science Board Question Paper 2024

SECTION-B

19. (A) (i) Expand the following terms: XML, PPP

Answer:

XML: Extensible Markup Language

PPP: Peer to Peer Protocol

 

(ii) Give one difference between circuit switching and packet switching.

Answer: The key difference between circuit switching and packet switching is that packet switching is connectionless, whereas circuit switching is connection-oriented

OR

(B) (i) Define the term web hosting.

Answer: Web hosting is a service that allows you to publish your website on the internet.

(ii) Name any two web browsers.

Answer: Google Chrome, Microsoft Edge (formerly Internet Explorer), Mozilla Firefox, and Apple’s Safari

 

20. The code given below accepts five numbers and displays whether they are even or odd:

Observe the following code carefully and rewrite it after removing all syntax and logical errors:

Underline all the corrections made.

def EvenOdd ()

for i in range (5):

               num=int(input(“Enter a number”)

               if num/2==0:

                      print(“Even”)

               else:

               print(“Odd”)

EvenOdd ()

 

Answer:

def EvenOdd ():#missing colon

         for i in range (5):

               num=int(input(“Enter a number”))#missing closing parenthesis

               if num%2==0:# Corrected the condition for checking even number

                       print(“Even”)

               else:

                      print(“Odd”)#indentation
EvenOdd ()

 

21. (A) Write a user defined function in Python named showGrades (S) which takes the dictionary S as an argument. The dictionary, S contains Name: [Eng, Math, Science] as key: value pairs. The function displays the corresponding grade obtained by the students according to the following grading rules:

 

Average of Eng, Math, Science Grade
>=90 A
<90 but >=60 B
<60 C

For example: Consider the following dictionary

S={“AMIT”: [92,86,64], “NAGMA”: [65,42,43], “DAVID”: [92,90,88]}

The output should be :

AMIT -B

NAGMA-C

DAVID -A

 

Answer:

def showGrades(S):
    for name, scores in S.items():
        average_score = sum(scores) / len(scores)
        if average_score >= 90:
            grade = 'A'
        elif average_score >= 60:
            grade = 'B'
        else:
            grade = 'C'
        print(f"{name} - {grade}")

# Example dictionary
S = {"AMIT": [92, 86, 64], "NAGMA": [65, 42, 43], "DAVID": [92, 90, 88]}

# Displaying grades
showGrades(S)

 

OR

(B) Write a user defined function in Python named Puzzle (W, N) which takes the argument was an English word and N as an integer and returns the string where every Nth alphabet of the word W is replaced with an underscore (“_”).

For example: if W contains the word “TELEVISION” and N is 3, then the function should return the string “TE_EV_SI_N”. Likewise for the word “TELEVISION” if N is 4, then the function should return “TEL_VIS_ON”.

 

Answer: 

def Puzzle(W, N):
    result = ''
    for i in range(len(W)):
        if (i + 1) % N == 0:  # Check if the current index is divisible by N
            result += '_'
        else:
            result += W[i]
    return result

# Example usage:
word = "TELEVISION"
N = 3
print(Puzzle(word, N))  # Output: TE_EV_SI_N

N = 4
print(Puzzle(word, N))  # Output: TEL_VIS_ON

 

Class 12 Computer Science Board Question Paper 2024

22. Write the output displayed on execution of the following Python code:

LS=[“HIMALAYA”, “NILGIRI”, “ALASKA”, “ALPS”]

D={}

for S in LS:

       if len (S) %4==0:

            D[S] = len(S)

for K in D:

         print (K,D [K], sep = “#”)

 

Answer: 

HIMALAYA#8
ALPS#4

 

23. (A) Write the Python statement for each of the following tasks using built-in functions/methods only:

(i) To remove the item whose key is “NISHA” from a dictionary named Students.

For example, if the dictionary Students contains (“ANITA”:90, “NISHA”:76, “ASHA”: 92), then after removal the dictionary should contain (“ANITA”:90, “ASHA”:92)

Answer: 

Students = {"ANITA": 90, "NISHA": 76, "ASHA": 92}
Students.pop("NISHA", None)  # Remove "NISHA" if it exists, otherwise do nothing
print (Students)

 

 

(ii) To display the number of occurrences of the substring “is” in a string named message.

For example if the string message contains “This is his book”, then the output will be 3.

 

Answer: 

message = "This is his book"
occurrences = message.count("is")
print(occurrences)

 

OR

(B) A tuple named subject stores the names of different subjects. Write the Python commands to convert the given tuple to a list and thereafter delete the last element of the list.

Answer: 

# Given tuple
subject = ("Math", "Science", "History", "English")

# Convert tuple to list
subject_list = list(subject)

# Delete the last element of the list
del subject_list[-1]

# Printing the modified list
print(subject_list)

 

24. (A) Ms. Veda created a table named Sports in a MySQL database, containing columns Game_id, P_Age and G_name.

After creating the table, she realized that the attribute, Category has to be added. Help her to write a command to add the Category column. Thereafter, write the command to insert the following record in the table:

Game_id: G42

P_Age: Above 18

G_name: Chess

Category: Senior

 

Answer:

ALTER TABLE Sports
ADD COLUMN Category VARCHAR(50);

INSERT INTO Sports VALUES (‘G42’, ‘Above 18’, ‘Chess’, ‘Senior’);

OR

(B) Write the SQL commands to perform the following tasks:

(i) View the list of tables in the database, Exam.

Answer:

USE EXAM;

SHOW TABLES;

 

(ii) View the structure of the table, Term1.

Answer:

DESCRIBE Term1;

Class 12 Computer Science Board Question Paper 2024

25. Predict the output of the following code:

def callon (b = 20, a = 10) :
    b = b + a
    a = b - a
    print ( b,"#",a)
    return b
x = 100
y = 200
x=callon (x, y)
print ( x ,"@",y)
y=callon (y)
print ( x ,"@",y )

 

Answer:

(300, ‘#’, 100)
(300, ‘@’, 200)
(210, ‘#’, 200)
(300, ‘@’, 210)

SECTION-C

26. Write the output on execution of the following Python code:

S = "Racecar Car Radar"
L = S.split()
for W in L:
    x = W.upper()
    if x ==x[::-1]:
        for I in x:
            print (I, end="*")
    else:
        for I in W:
            print (I, end ="#")
    print()

 

Answer:

R*A*C*E*C*A*R*
C#a#r#
R*A*D*A*R*

 

 

27. Consider the table ORDERS given below and write the output of the SQL queries that follow:

Class 12 Computer Science Board Question Paper 2024

 

(i) SELECT ITEM, SUM (QTY) FROM ORDERS GROUP BY ITEM;

Answer:

ITEM       | SUM(QTY)
—————————
RICE        | 48
PULSES  | 29
WHEAT  | 80

(ii) SELECT ITEM, QTY FROM ORDERS WHERE ORDATE BETWEEN ‘2023-11-01’ AND ‘2023-12-31’;

Answer:

ITEM      | QTY
——————-
RICE       | 25
WHEAT  | 28

(iii) SELECT ORDNO, ORDATE FROM ORDERS WHERE ITEM ‘WHEAT’ AND RATE>=60;

Answer:

ORDNO | ORDATE
—————————–
1007        | 2024-04-30

28. (A) Write a user defined function in Python named showInLines() which reads contents of a text file named STORY.TXT and displays every sentence in a separate line.

Assume that a sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!).

For example, if the content of file STORY. TXT is as follows:

Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell?

 

Then the function should display the file’s content as follows:

Our parents told us that we must eat vegetables to be healthy.

And it turns out, our parents were right!

So, what else did our parents tell?

 

Answer:

def showInLines():
    try:
        with open("STORY.TXT", "r") as file:
            content = file.read()
            sentences = []
            sentence = ""
            for char in content:
                sentence += char
                if char in ['.', '?', '!']:
                    sentences.append(sentence.strip())
                    sentence = ""
            if sentence:
                sentences.append(sentence.strip())
            for sentence in sentences:
                print(sentence)
    except FileNotFoundError:
        print("File not found.")
showInLines()

 

 

 

OR

(B) Write a function, c_words () in Python that separately counts and displays the number of uppercase and lowercase alphabets in a text file, Words.txt.

 

Answer:

def c_words():
    try:
        with open("Words.txt", "r") as file:
            content = file.read()
            lowercase_count = sum(1 for char in content if char.islower())
            uppercase_count = sum(1 for char in content if char.isupper())
            print("Number of lowercase alphabets:", lowercase_count)
            print("Number of uppercase alphabets:", uppercase_count)
    except FileNotFoundError:
        print("File not found.")
c_words()

 

29. Consider the table Projects given below:

Table Project

Based on the given table, write SQL queries for the following:

(i) Add the constraint, primary key to column P_id in the existing table Projects.

Answer: 

ALTER TABLE Projects
ADD PRIMARY KEY (P_id);

(ii) To change the language to Python of the project whose id is P002.

Answer:

UPDATE Projects
SET Language = ‘Python’
WHERE P_id = ‘P002’;

(iii) To delete the table Projects from MySQL database along with its data.

Answer:

DROP TABLE Projects;

 

30. Write the following user defined functions in Python and perform the specified operations on a stack named BigNums.

(i) PushBig(): It checks every number from the list Nums and pushes all such numbers which have 5 or more digits into the stack, BigNums.

(ii) PopBig(): It pops the numbers from the stack. BigNums and displays them. The function should also display “Stack Empty” when there are no more numbers left in the stack.

For example: If the list Nums contains the following data: Nums = [213,10025, 167, 254923, 14, 1297653, 31498, 386,92765] Then on execution of PushBig(), the stack BigNums should store: [10025, 254923, 1297653, 31498, 92765] And on execution of PopBig(), the following output should be displayed:

92765

31498

1297653

254923

10025

Stack Empty

 

Answer:

def PushBig(Nums, BigNums):
    for num in Nums:
        if len(str(num)) >= 5:
            BigNums.append(num)

def PopBig(BigNums):
    while BigNums:
        print(BigNums.pop())
    else:
        print("Stack Empty")

# List containing data
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]

# Creating an empty list to act as a stack
BigNums = []

# Pushing big numbers to the stack
PushBig(Nums, BigNums)

# Popping and displaying big numbers from the stack
PopBig(BigNums)

 

SECTION-D

31. Consider the tables Admin and Transport given below:

Table: Admin

S_id S_name Address S_type
S001 Sandhya Rohini Day Boarder
S002 Vedanshi Rohtak Day Scholar
S003 Vibhu Raj Nagar NULL
S004 Atharva Rampur Day Boarder

 

Table: Transport

S_id Bus_no Stop_name
S002 TSS10 Sarai Kale Khan
S004 TSS12 Sainik Vihar
S005 TSS10 Kamla Nagar

Write SQL queries for the following:

(i) Display the student name and their stop name from the tables Admin and Transport.

Answer:

SELECT A.S_name, T.Stop_name
FROM Admin A
JOIN Transport T ON A.S_id = T.S_id;

 

(ii) Display the number of students whose S_type is not known.

Answer:

SELECT COUNT(*)
FROM Admin
WHERE S_type IS NULL;

 

(iii) Display all details of the students whose name starts with ‘V’.

Answer:

SELECT *
FROM Admin
WHERE S_name LIKE ‘V%’;

 

(iv) Display student id and address in alphabetical order of student name, from the table Admin.

Answer:

SELECT S_id, Address
FROM Admin
ORDER BY S_name;

 

32. Sangeeta is a Python programmer working in a computer hardware company. She has to maintain the records of the peripheral devices. She created a csv file named Peripheral.csv, to store the details. The structure of Peripheral.csv is:

[P_id, P_name, Price]

where

P_id is Peripheral device ID (integer)

P_name is Peripheral device name (String)

Price is Peripheral device price (integer)

 

Sangeeta wants to write the following user defined functions:

Add_Device(): to accept a record from the user and add it to a csv file, Peripheral.csv.

Count_Device(): To count and display number of peripheral devices whose price is less than 1000.

 

Answer:

import csv

def Add_Device():
    try:
        with open("Peripheral.csv", "a", newline='') as file:
            writer = csv.writer(file)
            P_id = int(input("Enter Peripheral device ID: "))
            P_name = input("Enter Peripheral device name: ")
            Price = int(input("Enter Peripheral device price: "))
            writer.writerow([P_id, P_name, Price])
            print("Device added successfully.")
    except Exception as e:
        print("An error occurred:", e)

def Count_Device():
    try:
        count = 0
        with open("Peripheral.csv", "r") as file:
            reader = csv.reader(file)
            next(reader)  # Skip header
            for row in reader:
                if int(row[2]) < 1000:
                    count += 1
        print("Number of peripheral devices with price less than 1000:", count)
    except Exception as e:
        print("An error occurred:", e)

# Example usage:
Add_Device()
Count_Device()

 

 

SECTION-E

33. Infotainment Ltd. is an event management company with its prime office located in Bengaluru. The company is planning to open its new division at three different locations in Chennai named as Vajra, Trishula and Sudershana.

You, as a networking expert need to suggest solutions to the questions in part (i) to (v), keeping in mind the distances and other given parameters.

Network Question

Distances between various locations:

Vajra to Trishula 350 m
Trishula to Sudershana 415 m
Sudershana to Vajra 300 m
Bengaluru Office to Chennai 2000 km

 

Number of computers installed at various locations:

Vajra 120
Sudershana 75
Trishula 65
Bengaluru Office 250

 

(i) Suggest and draw the cable layout to efficiently connect various locations in Chennai division for connecting the digital devices.

Answer: 

Cable Layout

(ii) Which block in Chennai division should host the server ? Justify your answer.

Answer: The block that should be made the server in Chennai Campus is the Vajra block. This is because it has the highest number of computers (120).

 

(iii) Which fast and effective wired transmission medium should be used to connect the prime office at Bengaluru with the Chennai division?

Answer: Fibre optic cable

 

(iv) Which network device will be used to connect the digital devices within each location of Chennai division so that they may communicate with each other?

Answer: Hub/Switch

 

(v) A considerable amount of data loss is noticed between different locations of the Chennai division, which are connected in the network. Suggest a networking device that should be installed to refresh the data and reduce the data loss during transmission to and from different locations of Chennai division.

Answer: Network switch/Repeater

 

34. (A) (i) Differentiate between ‘w’ and ‘a’ file modes in Python. 

Answer:

‘w’ mode (write mode): Opens a file for writing. If the file exists, it’s truncated (emptied) before writing. If it doesn’t exist, a new file is created. Writing starts from the beginning of the file.

‘a’ mode (append mode): Opens a file for writing. It appends data to the end of the file if it exists; otherwise, it creates a new file. Writing starts from the end of the file.

 

(ii) Consider a binary file, items.dat, containing records stored in the given format:

[item_id: [item_name, amount])

Write a function, Copy_new(), that copies all records whose amount is greater than 1000 from items.dat to new_items. dat.

def Copy_new():
    try:
        with open("items.dat", "rb") as infile, open("new_items.dat", "wb") as outfile:
            while True:
                try:
                    # Read a record from items.dat
                    record = eval(infile.readline().decode().strip())
                    # Check if the amount is greater than 1000
                    if record[1] > 1000:
                        # Write the qualifying record to new_items.dat
                        outfile.write(str(record).encode() + b'\n')
                except EOFError:
                    break
    except FileNotFoundError:
        print("One or both of the files does not exist.")

Copy_new()

 

 

OR

(B) (i) What is the advantage of using with clause while opening a data file in Python? Also give syntax of with clause.

Answer:

The ‘with’ statement in Python provides a convenient way to manage a file. It ensures proper handling of file by automatically closing that when it is no longer needed.

Syntax:

with open(filename, mode) as file:

(ii) A binary file, EMP. DAT has the following structure: [Emp_Id, Name, Salary]

where

Emp_Id: Employee id

Name: Employee Name

Salary: Employee Salary.

Write a user defined function, disp_Detail (), that would read the contents of the file EMP. DAT and display the details of those employees whose salary is below 25000.

Answer:

def disp_Detail():
    try:
        with open("EMP.DAT", "rb") as file:
            while True:
                try:
                    # Read one record from the file
                    emp_id, name, salary = eval(file.readline().decode().strip())
                    # Check if salary is below 25000
                    if salary < 25000:
                        # Display details of the employee
                        print(f"Employee ID: {emp_id}, Name: {name}, Salary: {salary}")
                except EOFError:
                    break
    except FileNotFoundError:
        print("EMP.DAT file not found.")
disp_Detail()

 

 

 

35. (A) (i) Define cartesian product with respect to RDBMS.

Answer:

Cartesian product in RDBMS refers to combining every row from one table with every row from another table(s), resulting in a potentially large result set. It’s achieved using the CROSS JOIN keyword in SQL and can lead to performance issues with large datasets.

 

(ii) Sunil wants to write a program in Python to update the quantity to 20 of the records whose item code is 111 in the table named shop in MySQL database named Keeper.

The table shop in MySQL contains the following attributes:

Item_code: Item code (Integer)

Item_name: Name of item (String)

Qty: Quantity of item (Integer)

Price: Price of item (Integer)

 

Consider the following to establish connectivity between Python and MySQL:

Username: admin

Password: Shopping

Host: localhost

import mysql.connector

# Establish connection to MySQL database
try:
    connection = mysql.connector.connect(
        host="localhost",
        user="admin",
        password="Shopping",
        database="Keeper"
    )

    cursor = connection.cursor()

    # Update quantity to 20 for item code 111
    sql_query = "UPDATE shop SET Qty = 20 WHERE Item_code = 111"
    cursor.execute(sql_query)
    connection.commit()

    print("Records updated successfully.")

except mysql.connector.Error as error:
    print("Error:", error)

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed.")

 

OR

(B) (i) Give any two features of SQL.

Answer:

1. SQL is Declarative: SQL allows users to specify what data they want to retrieve or manipulate, rather than how to retrieve it. Users specify queries in SQL without needing to specify the steps or algorithms used to perform the query.

2. SQL is Set-based: SQL operates on sets of data rather than individual records. This allows users to perform operations on entire sets of data at once, making it efficient for working with large datasets.

 

(ii) Sumit wants to write a code in Python to display all the details of the passengers from the table flight in MySQL database, Travel. The table contains the following attributes:

F_code: Flight code (String)

F_name: Name of flight (String)

Source: Departure city of flight (String)

Destination: Destination city of flight (String)

Consider the following to establish connectivity between Python and MySQL:

Username: root

Password: airplane

Host: localhost

 

Answer:

import mysql.connector

# Establish connection to MySQL database
try:
    connection = mysql.connector.connect(
        host="localhost",
        user="root",
        password="airplane",
        database="Travel"
    )

    cursor = connection.cursor()

    # Select all details of passengers from the flight table
    sql_query = "SELECT * FROM flight"
    cursor.execute(sql_query)

    # Fetch all rows
    passengers = cursor.fetchall()

    # Display details of passengers
    for passenger in passengers:
        print(passenger)

except mysql.connector.Error as error:
    print("Error:", error)

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed.")

 

 

 

 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved