KnowledgeBoat Logo
OPEN IN APP

Sample 2025

Solved 2025 Sample Question Paper CBSE Class 12 Computer Science (083)

Class 12 - CBSE Computer Science Solved Question Papers



Section A (1 Mark Each)

Question 1

State True or False:

The Python interpreter handles logical errors during code execution.

Answer

False

Reason — The Python interpreter handles syntax errors during code execution, but it does not handle logical errors. Logical errors, also known as semantic errors, occur when the code is syntactically correct but does not produce the expected output due to incorrect logic or algorithm. These types of errors are caught during the testing and debugging phase, not during code execution by the interpreter.

Question 2

Identify the output of the following code snippet:

text = "PYTHONPROGRAM"
text = text.replace('PY', '#')
print(text)
  1. #THONPROGRAM
  2. ##THON#ROGRAM
  3. #THON#ROGRAM
  4. #YTHON#ROGRAM

Answer

#THONPROGRAM

Reason — The replace() method in Python searches for a specified substring and replaces it with another. In the given code, the substring 'PY' in the string "PYTHONPROGRAM" is replaced with the character '#'. As a result, the string "PYTHONPROGRAM" becomes "#THONPROGRAM", and that's the output displayed.

Question 3

Which of the following expressions evaluates to False ?

  1. not(True) and False
  2. True or False
  3. not(False and True)
  4. True and not(False)

Answer

not(True) and False

Reason

  1. not(True) and False evaluates to False and False, which is False.
  2. True or False evaluates to True.
  3. not(False and True) evaluates to not(False), which is True.
  4. True and not(False) evaluates to True and True, which is True.

Question 4

What is the output of the expression ?

country = 'International'
print(country.split("n"))
  1. ('I', 'ter', 'atio', 'aI')
  2. ['I', 'ter', 'atio', 'al']
  3. ['I', 'n', 'ter', 'n', 'atio', 'n', 'al']
  4. Error

Answer

['I', 'ter', 'atio', 'al']

Reason — The code defines a string country = 'International' and uses the split("n") method to split the string at each occurrence of the letter "n". This breaks the string into a list of parts: ['I', 'ter', 'atio', 'al'], with each occurrence of "n" removed and the remaining substrings stored as separate elements in the list. The print() function then outputs this list.

Question 5

What will be the output of the following code snippet ?

message = "World Peace"
print(message[-2::-2])

Answer

Output
ce lo
Explanation
  1. The code message[-2::-2] starts from the second-last (-2) character of the string "World Peace", which is "c".

  2. It moves backwards in steps of 2 to select every second character going towards the start of the string.

  3. The traversal goes as follows:

    • Index -2: Character is "c".
    • Index -4: Character is "e".
    • Index -6: Character is a space (" ").
    • Index -8: Character is "l".
    • Index -10: Character is "o".
  4. The output is "ce lo".

Question 6

What will be the output of the following code ?

tuple1 = (1, 2, 3)
tuple2 = tuple1
tuple1 += (4, )
print(tuple1 == tuple2)
  1. True
  2. False
  3. tuple1
  4. Error

Answer

False

Reason — In the above code, tuple1 is initially assigned the tuple (1, 2, 3), and tuple2 references the same tuple. When the line tuple1 += (4, ) is executed, it modifies tuple1 to (1, 2, 3, 4) because the += operator creates a new tuple rather than modifying the existing one. Thus, tuple1 now contains (1, 2, 3, 4), while tuple2 remains (1, 2, 3). Therefore, the expression tuple1 == tuple2 evaluates to False.

Question 7

If my_dict is a dictionary as defined below, then which of the following statements will raise an exception ?

my_dict = {'apple' : 10, 'banana' : 20, 'orange' : 30}

  1. my_dict.get('orange')
  2. print(my_dict['apple', 'banana'])
  3. my_dict['apple'] = 20
  4. print(str(my_dict))

Answer

print(my_dict['apple', 'banana'])

Reason — In Python dictionaries, keys must be accessed individually or as a single key. The expression my_dict['apple', 'banana'] attempts to use a tuple as a key (i.e., ('apple', 'banana')), which does not exist in my_dict. As a result, this will raise an Error. The other statements will not raise exceptions; my_dict.get('orange') will return 30, my_dict['apple'] = 20 will update the value for the key 'apple', and print(str(my_dict)) will print the dictionary as a string.

Question 8

What does the list.remove(x) method do in Python ?

  1. Removes the element at index x from the list
  2. Removes the first occurrence of value x from the list
  3. Removes all occurrences of value x from the list
  4. Removes the last occurrence of value x from the list

Answer

Removes the first occurrence of value x from the list.

Reason — The list.remove(x) method in Python searches for the first occurrence of the value x in the list and removes it. If the specified value is not found, it raises an Error.

Question 9

If a table which has one Primary key and two alternate keys. How many Candidate keys will this table have ?

  1. 1
  2. 2
  3. 3
  4. 4

Answer

3

Reason — In a table, the primary key uniquely identifies each record, and alternate keys also uniquely identify records but are not the primary key. In this case, with one primary key and two alternate keys, the table will have three candidate keys in total: one primary key and two alternate keys. Candidate keys are potential keys that can uniquely identify records in a table.

Question 10

Write the missing statement to complete the following code:

file = open("example.txt", "r")
data = file.read(100)
............... #Move the file pointer to the beginning of the file
next_data = file.read(50)
file.close()

Answer

file.seek(0)

Reason — To move the file pointer to the beginning of the file, we can use the seek() method. When we pass 0 as the offset to this function, it moves the file pointer to the beginning of the file.

So the complete code is:

file = open("example.txt", "r")
data = file.read(100)
file.seek(0)  # Move the file pointer to the beginning of the file
next_data = file.read(50)
file.close()

Question 11

State whether the following statement is True or False:

The finally block in Python is executed only if no exception occurs in the try block.

Answer

False

Reason — The finally block in Python is always executed after the try block, regardless of whether an exception occurred or not.

Question 12

What will be the output of the following code ?

c = 10
def add():
    global c
    c = c + 2
    print(c, end = '#')
add()
c = 15
print(c, end = '%')
  1. 12%15#
  2. 15#12%
  3. 12#15%
  4. 12%15#

Answer

12#15%

Reason

  1. The variable c is initially set to 10.
  2. The function add() is defined. Inside this function, the global keyword is used to indicate that the variable c refers to the global variable defined outside the function.
  3. Inside add(): When add() is called:
    • The value of c (which is 10) is accessed.
    • It is then incremented by 2, making c equal to 12.
    • The new value of c (12) is printed, followed by a # symbol.
  4. After calling the function, the global c is now 12. However, it is then explicitly set to 15.
  5. Finally, the new value of c (15) is printed, followed by a % symbol.

Question 13

Which SQL command can change the degree of an existing relation ?

Answer

The SQL command that can change the degree of an existing relation (table) is ALTER TABLE.

Question 14

What will be the output of the query ?

SELECT * FROM products WHERE product_name LIKE 'App%';
  1. Details of all products whose names start with 'App'
  2. Details of all products whose names end with 'App'
  3. Names of all products whose names start with 'App'
  4. Names of all products whose names end with 'App'

Answer

Details of all products whose names start with 'App'

Reason — The SELECT * statement indicates that every column of data should be returned for each matching record. It uses the LIKE operator with the pattern 'App%', where the % wildcard represents any sequence of characters. Therefore, this query will return details of all products from the products table where the product_name starts with 'App', including any characters that may follow.

Question 15

In which datatype the value stored is padded with spaces to fit the specified length.

  1. DATE
  2. VARCHAR
  3. FLOAT
  4. CHAR

Answer

CHAR

Reason — The CHAR data type in SQL is used to store fixed-length strings. When a value is stored in a CHAR field, it is padded with spaces to fit the specified length.

Question 16

Which aggregate function can be used to find the cardinality of a table ?

  1. sum()
  2. count()
  3. avg()
  4. max()

Answer

count()

Reason — The count() aggregate function is used to find the cardinality of a table, which refers to the number of rows in that table.

Question 17

Which protocol is used to transfer files over the Internet ?

  1. HTTP
  2. FTP
  3. PPP
  4. HTTPS

Answer

FTP

Reason — The File Transfer Protocol (FTP) is used for transferring files over the Internet. It allows users to upload, download, and manage files on remote servers.

Question 18

Which network device is used to connect two networks that use different protocols ?

  1. Modem
  2. Gateway
  3. Switch
  4. Repeater

Answer

Gateway

Reason — A gateway is a network device that connects two networks that use different protocols, enabling communication between them.

Question 19

Which switching technique breaks data into smaller packets for transmission, allowing multiple packets to share the same network resources.

Answer

Packet switching is a method of data transmission where data is broken into smaller packets before being sent over the network. Each packet can take different routes to reach the destination, allowing multiple packets from various sources to share the same network resources simultaneously.

Question 20

Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.

Reasoning (R): This is because Python functions automatically assign default values to positional arguments.

  1. Both A and R are true, and R is the correct explanation of A.
  2. Both A and R are true, and R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
Positional arguments must be passed in the order they are defined in the function signature in Python. Python does not automatically assign default values to positional arguments. Default values must be explicitly defined in the function signature, if not provided, the function will raise an error.

Question 21

Assertion (A): A SELECT command in SQL can have both WHERE and HAVING clauses.

Reasoning (R): WHERE and HAVING clauses are used to check conditions, therefore, these can be used interchangeably.

  1. Both A and R are true, and R is the correct explanation of A.
  2. Both A and R are true, and R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
A SQL SELECT command can have both WHERE and HAVING clauses. The WHERE clause filters records before any grouping occurs, while the HAVING clause filters records after grouping. Therefore, they cannot be used interchangeably as they operate at different stages of query execution.

Section B (2 Marks Each)

Question 22

How is a mutable object different from an immutable object in Python ?

Identify one mutable object and one immutable object from the following:

(1, 2), [1, 2], {1:1, 2:2}, '123'

Answer

In Python, a mutable object can be changed after it is created (e.g., lists, dictionaries), while an immutable object cannot be modified after its creation (e.g., tuples, strings).

An example of a mutable object from the given options is [1, 2] (list) and {1:1, 2:2} (dictionary). [Write any one]

An example of an immutable object from the options is '123' (string) and (1, 2) (tuple). [Write any one]

Question 23

Give two examples of each of the following:

  1. Arithmetic operators
  2. Relational operators

Answer

  1. Arithmetic Operators — +, -

  2. Relational Operators — >, ==

Question 24

If L1 = [1, 2, 3, 2, 1, 2, 4, 2, ...], and L2 = [10, 20, 30, ...], then

(Answer using builtin functions only)

  1. (a) Write a statement to count the occurrences of 4 in L1.
    OR
    (b) Write a statement to sort the elements of list L1 in ascending order.

  2. (a) Write a statement to insert all the elements of L2 at the end of L1.
    OR
    (b) Write a statement to reverse the elements of list L2.

Answer

  1. (a) L1.count(4)
    OR
    (b) L1.sort()

  2. L1.extend(L2)
    OR
    (b) L2.reverse()

Question 25

Identify the correct output(s) of the following code. Also write the minimum and the maximum possible values of the variable b.

import random
a = "Wisdom"
b = random.randint(1, 6)
for i in range(0, b, 2):
    print(a[i], end = '#')
  1. W#
  2. W#i#
  3. W#s#
  4. W#i#s#

Answer

W#, W#s#

Minimum and maximum possible values of the variable b is 1, 6.

Reason — The code imports the random module and initializes a string variable a with the value "Wisdom". It then generates a random integer b between 1 and 6, inclusive. A for loop iterates over a range from 0 to b in steps of 2, which means it only considers even indices (0, 2, 4) of the string a. In each iteration, it prints the character at the current index i of the string a, followed by a '#' character, without moving to a new line.

For possible values of b:

For b = 1:

  • Range: range(0, 1, 2) → Only includes 0
  • Step 1: i = 0 → Prints W#
  • Final Output: W#

For b = 2:

  • Range: range(0, 2, 2) → Only includes 0
  • Step 1: i = 0 → Prints W#
  • Final Output: W#

For b = 3:

  • Range: range(0, 3, 2) → Includes 0, 2
  • Step 1: i = 0 → Prints W#
  • Step 2: i = 2 → Prints s#
  • Final Output: W#s#

For b = 4:

  • Range: range(0, 4, 2) → Includes 0, 2
  • Step 1: i = 0 → Prints W#
  • Step 2: i = 2 → Prints s#
  • Final Output: W#s#

For b = 5:

  • Range: range(0, 5, 2) → Includes 0, 2, 4
  • Step 1: i = 0 → Prints W#
  • Step 2: i = 2 → Prints s#
  • Step 3: i = 4 → Prints o#
  • Final Output: W#s#o#

For b = 6:

  • Range: range(0, 6, 2) → Includes 0, 2, 4
  • Step 1: i = 0 → Prints W#
  • Step 2: i = 2 → Prints s#
  • Step 3: i = 4 → Prints o#
  • Final Output: W#s#o#

Question 26

The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.

def swap_first_last(tup)
    if len(tup) < 2:
    return tup
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)

Answer

def swap_first_last(tup) # Error 1
    if len(tup) < 2:
    return tup  # Error 2
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0])  # Error 3
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result) # Error 4

Error 1 — The function header is missing a colon (:) at the end, which is required to define a function in Python.

Error 2 — The return statement needs to be indented because it is the part of the if block.

Error 3 — Comma should be added after tup[0] to ensure it is treated as a tuple. Without the comma, (tup[0]) is treated as an integer.

Error 4 — Comma should be added in the print statement to properly separate the string from the variable.

The corrected code is:

def swap_first_last(tup):  
    if len(tup) < 2:        
        return tup 
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0],)
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: ", result) 

Question 27-I(a)

What constraint should be applied on a table column so that duplicate values are not allowed in that column, but NULL is allowed.

Answer

To prevent duplicate values in a table column while allowing NULL values, we should use the UNIQUE constraint. The UNIQUE constraint ensures that all values in the specified column are different, but it permits multiple NULLs since NULL is considered distinct from any other value.

Question 27-I(b)

What constraint should be applied on a table column so that NULL is not allowed in that column, but duplicate values are allowed.

Answer

To ensure that NULL values are not allowed in a table column while allowing duplicate values, we should use the NOT NULL constraint. The NOT NULL constraint ensures that every entry in the specified column must have a value (i.e., it cannot be NULL), but it allows duplicate values.

Question 27-II(a)

Write an SQL command to remove the Primary Key constraint from a table, named MOBILE. M_ID is the primary key of the table.

Answer

ALTER TABLE MOBILE 
DROP PRIMARY KEY;

Question 27-II(b)

Write an SQL command to make the column M_ID the Primary Key of an already existing table, named MOBILE.

Answer

ALTER TABLE MOBILE 
ADD PRIMARY KEY (M_ID);

Question 28(a)

List one advantage and one disadvantage of star topology.

Answer

Advantage

Ease of service — Network extension is easy.

Disadvantage

Central node dependency — Failure of switch/hub results in failure of the network.

Question 28(b)

Expand the term SMTP. What is the use of SMTP ?

Answer

SMTP stands for Simple Mail Transfer Protocol.

It is the standard protocol for sending emails across the Internet.

Section C (3 Marks Each)

Question 29(a)

Write a Python function that displays all the words containing @cmail from a text file "Emails.txt".

Answer

Suppose the file "Emails.txt" contains the following text:

jagan@cmail.com 
aliya@gmail.com 
ali@cmail.net 
sara@cmail.edu 
mahi@yahoo.com.
def display_words():
    file = open("Emails.txt", 'r')
    content = file.read()
    words = content.split()            
    for word in words:
        if '@cmail' in word:
            print(word, end = ' ')
    file.close()
display_words()
Output
jagan@cmail.com ali@cmail.net sara@cmail.edu

Question 29(b)

Write a Python function that finds and displays all the words longer than 5 characters from a text file "Words.txt".

Answer

Suppose the file "Words.txt" contains the following text:

The quick brown fox jumps over the lazy dog and runs swiftly through the forest
def display():
    file = open("Words.txt", 'r')
    content = file.read()
    words = content.split()
    for word in words:
        if len(word) > 5:
            print(word, end = ' ')
    file.close()
display()
Output
swiftly through forest 

Question 30(a)

You have a stack named BooksStack that contains records of books. Each book record is represented as a list containing book_title, author_name, and publication_year.

Write the following user-defined functions in Python to perform the specified operations on the stack BooksStack:

  1. push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book record new_book as arguments and pushes the new book record onto the stack.

  2. pop_book(BooksStack): This function pops the topmost book record from the stack and returns it. If the stack is already empty, the function should display "Underflow".

  3. peep(BookStack): This function displays the topmost element of the stack without deleting it. If the stack is empty, the function should display 'None'.

Answer

1.

def push_book(BooksStack, new_book): 
  BooksStack.append(new_book)

2.

def pop_book(BooksStack): 
    if not BooksStack: 
        print("Underflow") 
    else: 
        return(BookStack.pop())

3.

def peep(BooksStack): 
    if not BooksStack: 
        print("None") 
    else: 
        print(BookStack[-1])

Question 30(b)

Write the definition of a user-defined function push_even(N) which accepts a list of integers in a parameter N and pushes all those integers which are even from the list N into a Stack named EvenNumbers.

Write function pop_even() to pop the topmost number from the stack and return it. If the stack is already empty, the function should display "Empty".

Write function Disp_even() to display all element of the stack without deleting them. If the stack is empty, the function should display 'None'.

For example: If the integers input into the list VALUES are: [10, 5, 8, 3, 12]

Then the stack EvenNumbers should store: [10, 8, 12]

Answer

def push_even(N):
    EvenNumbers = []
    for num in N:
        if num % 2 == 0:
            EvenNumbers.append(num)
    return EvenNumbers

VALUES = []

for i in range(5):
    VALUES.append(int(input("Enter an integer: ")))

EvenNumbers = push_even(VALUES)

def pop_even():
    if not EvenNumbers:
        print("Underflow")
    else:
        print(EvenNumbers.pop())
pop_even()

def Disp_even():
    if not EvenNumbers:
        print("None")
    else:
        print(EvenNumbers[-1])
Disp_even()
Output
Enter an integer: 10
Enter an integer: 5
Enter an integer: 8
Enter an integer: 3
Enter an integer: 12
12
8

Question 31(a)

Predict the output of the following code:

d = {"apple": 15, "banana": 7, "cherry": 9} 
str1 = "" 
for key in d: 
    str1 = str1 + str(d[key]) + "@" + "\n"
str2 = str1[:-1] 
print(str2) 

Answer

Output
15@
7@
9@
Explanation
  1. Initialization:
  • A dictionary d is created with three key-value pairs.
  • An empty string str1 is initialized.
  1. Iteration:

    The for loop iterates over each key in the dictionary:

  • For "apple": str1 becomes "15@\n" (value 15 followed by "@" and a newline).
  • For "banana": str1 becomes "15@\n7@\n" (adding value 7 followed by "@" and a newline).
  • For "cherry": str1 becomes "15@\n7@\n9@\n" (adding value 9 followed by "@" and a newline).
  1. The line str2 = str1[:-1] removes the last newline character from str1, resulting in str2 being "15@\n7@\n9@".

  2. Finally, print(str2) outputs the content of str2.

Question 31(b)

Predict the output of the following code:

line = [4, 9, 12, 6, 20] 
for I in line: 
   for j in range(1, I%5): 
       print(j, '#', end="") 
   print() 

Answer

Output
1 #2 #3 #
1 #2 #3 #
1 #


Explanation
  1. The list line contains the values [4, 9, 12, 6, 20].

  2. The outer loop iterates over each element (I) in the line list.

    • First Iteration (I = 4):

      I % 5 = 4 % 5 = 4
      Inner Loop Range: range(1, 4) → This generates the numbers 1, 2, 3.
      Output: 1 #2 #3 #

    • Second Iteration (I = 9):

      I % 5 = 9 % 5 = 4
      Inner Loop Range: range(1, 4) → This generates the numbers 1, 2, 3.
      Output: 1 #2 #3 #

    • Third Iteration (I = 12):

      I % 5 = 12 % 5 = 2
      Inner Loop Range: range(1, 2) → This generates the number 1.
      Output: 1 #

    • Fourth Iteration (I = 6):

      I % 5 = 6 % 5 = 1
      Inner Loop Range: range(1, 1) → This generates no numbers (empty range).
      Print: No output for this iteration (just a new line is printed).

    • Fifth Iteration (I = 20):

      I % 5 = 20 % 5 = 0
      Inner Loop Range: range(1, 0) → This generates no numbers (empty range).
      Print: No output for this iteration (just a new line is printed).

  3. The final output of the code will be:

1 #2 #3 #
1 #2 #3 #
1 #


Section D (4 Marks Each)

Question 32

Consider the table ORDERS as given below

O_IdC_NameProductQuantityPrice
1001JitendraLaptop112000
1002MustafaSmartphone210000
1003DhwaniHeadphone11500

Note: The table contains many more records than shown here.

A) Write the following queries:

(I) To display the total Quantity for each Product, excluding Products with total Quantity less than 5.

(II) To display the orders table sorted by total price in descending order.

(III) To display the distinct customer names from the Orders table.

(IV) Display the sum of Price of all the orders for which the quantity is null.

OR

B) Write the output

(I) Select c_name, sum(quantity) as total_quantity from orders group by c_name;

(II) Select * from orders where product like '%phone%';

(III) Select o_id, c_name, product, quantity, price from orders where price between 1500 and 12000;

(IV) Select max(price) from orders;

Answer

(A)

(I)

SELECT Product, SUM(Quantity)
FROM ORDERS
GROUP BY Product
HAVING SUM(Quantity) >= 5;

(II)

SELECT *
FROM ORDERS
ORDER BY Price DESC;

(III)

SELECT DISTINCT C_Name
FROM ORDERS;

(IV)

SELECT SUM(Price) AS Total_Price
FROM ORDERS
WHERE Quantity IS NULL;

OR

(B)

(I) Select c_name, sum(quantity) as total_quantity from orders group by c_name;

Output
+----------+----------------+
| c_name   | total_quantity |
+----------+----------------+
| Jitendra |              1 |
| Mustafa  |              2 |
| Dhwani   |              1 |
+----------+----------------+

(II) Select * from orders where product like '%phone%';

Output
+------+---------+------------+----------+-------+
| O_Id | C_Name  | Product    | Quantity | Price |
+------+---------+------------+----------+-------+
| 1002 | Mustafa | Smartphone |        2 | 10000 |
| 1003 | Dhwani  | Headphone  |        1 |  1500 |
+------+---------+------------+----------+-------+

(III) Select o_id, c_name, product, quantity, price from orders where price between 1500 and 12000;

Output
+------+----------+------------+----------+-------+
| o_id | c_name   | product    | quantity | price |
+------+----------+------------+----------+-------+
| 1001 | Jitendra | Laptop     |        1 | 12000 |
| 1002 | Mustafa  | Smartphone |        2 | 10000 |
| 1003 | Dhwani   | Headphone  |        1 |  1500 |
+------+----------+------------+----------+-------+

(IV) Select max(price) from orders;

Output
+------------+
| max(price) |
+------------+
|      12000 |
+------------+

Question 33

A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following data:

  • Name of a country
  • Population of the country
  • Sample Size (Number of persons who participated in the survey in that country)
  • Happy (Number of persons who accepted that they were Happy)

For example, a sample record of the file may be:

[‘Signiland’, 5673000, 5000, 3426]

Write the following Python functions to perform the specified operations on this file:

(I) Read all the data from the file in the form of a list and display all those records for which the population is more than 5000000.

(II) Count the number of records in the file.

Answer

Let the "Happiness.csv" file contain the following data:

Signiland, 5673000, 5000, 3426
Happiland, 4500000, 4000, 3200
Joyland, 8000000, 6000, 5000
Cheerland, 3000000, 3500, 2500

(I)

def show(): 
    file = open("Happiness.csv",'r') 
    records=csv.reader(file) 
    for i in records: 
        if int(i[1])>5000000: 
            print(i) 
    file.close() 
Output
['Signiland', '5673000', '5000', '3426']
['Joyland', '8000000', '6000', '5000']

(II)

def Count_records(): 
    f = open("Happiness.csv",'r') 
    records=csv.reader(f) 
    count=0 
    for i in records: 
            count+=1 
    print(count) 
    f.close() 
Output
4

Question 34

Saman has been entrusted with the management of Law University Database. He needs to access some information from FACULTY and COURSES tables for a survey analysis. Help him extract the following information by writing the desired SQL queries as mentioned below.

Table: FACULTY

F_IDFNameLNameHire_DateSalary
102AmitMishra12-10-199812000
103NitinVyas24-12-19948000
104RakshitSoni18-5-200114000
105RashmiMalhotra11-9-200411000
106SulekhaSrivastava5-6-200610000

Table: COURSES

C_IDF_IDCNameFees
C21102Grid Computing40000
C22106System Design16000
C23104Computer Security8000
C24106Human Biology15000
C25102Computer Network20000
C26105Visual Basic6000

(I) To display complete details (from both the tables) of those Faculties whose salary is less than 12000.

(II) To display the details of courses whose fees is in the range of 20000 to 50000 (both values included).

(III) To increase the fees of all courses by 500 which have "Computer" in their Course names.

(IV)

(A) To display names (FName and LName) of faculty taking System Design.

OR

(B) To display the Cartesian Product of these two tables.

Answer

(I)

SELECT * FROM FACULTY, COURSES 
WHERE Salary < 12000 AND FACULTY.F_ID = COURSES.F_ID;

(II)

SELECT * 
FROM COURSES 
WHERE Fees BETWEEN 20000 AND 50000;

(III)

UPDATE COURSES
SET Fees = Fees + 500
WHERE CName LIKE '%Computer%';

(IV)

(A)

SELECT FName, LName 
FROM FACULTY, COURSES 
WHERE CName = 'System Design' AND
FACULTY.F_ID = COURSES.F_ID;

OR

(B)

SELECT * 
FROM FACULTY, COURSES;

Question 35

A table, named STATIONERY, in ITEMDB database, has the following structure:

FieldType
itemNoint(11)
itemNamevarchar(15)
pricefloat
qtyint(11)

Write the following Python function to perform the specified operation:

AddAndDisplay(): To input details of an item and store it in the table STATIONERY. The function should then retrieve and display all records from the STATIONERY table where the Price is greater than 120.

Assume the following for Python-Database connectivity:

Host: localhost, User: root, Password: Pencil

Answer

import mysql.connector

def AddAndDisplay():
    db = mysql.connector.connect(
            host="localhost",
            user="root",
            password="Pencil",
            database="ITEMDB"
        )
    cursor = db.cursor()
    item_no = int(input("Enter Item Number: "))
    item_name = input("Enter Item Name: ")
    price = float(input("Enter Price: "))
    qty = int(input("Enter Quantity: "))
    insert_query = "INSERT INTO STATIONERY VALUES ({}, {}, {}, {})"
    insert_query = insert_query.format(item_no, item_name, price, qty)
    cursor.execute(insert_query)
    db.commit()
    select_query = "SELECT * FROM STATIONERY WHERE price > 120"
    cursor.execute(select_query)
    results = cursor.fetchall()
    for record in results:
        print(record)
            
AddAndDisplay()

Section E (5 Marks Each)

Question 36

Surya is a manager working in a recruitment agency. He needs to manage the records of various candidates. For this, he wants the following information of each candidate to be stored:

  • Candidate_ID – integer
  • Candidate_Name – string
  • Designation – string
  • Experience – float

You, as a programmer of the company, have been assigned to do this job for Surya.

(I) Write a function to input the data of a candidate and append it in a binary file.

(II) Write a function to update the data of candidates whose experience is more than 10 years and change their designation to "Senior Manager".

(III) Write a function to read the data from the binary file and display the data of all those candidates who are not "Senior Manager".

Answer

(I)

import pickle 
 
def input_candidates(): 
    candidates = [] 
    n = int(input("Enter the number of candidates you want to add: ")) 
    for i in range(n): 
        candidate_id = int(input("Enter Candidate ID: ")) 
        candidate_name = input("Enter Candidate Name: ") 
        designation = input("Enter Designation: ") 
        experience = float(input("Enter Experience (in years): ")) 
        candidates.append([candidate_id, candidate_name, designation, 
experience]) 
    return candidates

candidates_list = input_candidates() 
 
def append_candidate_data(candidates): 
    with open('candidates.bin', 'ab') as file: 
        for candidate in candidates: 
            pickle.dump(candidate, file) 
    print("Candidate data appended successfully.") 
 
append_candidate_data(candidates_list)

(II)

import pickle 
 
def update_senior_manager(): 
    updated_candidates = [] 
    try: 
        with open('candidates.bin', 'rb') as file: 
            while True: 
                try: 
                    candidate = pickle.load(file) 
                    if candidate[3] > 10:  # If experience > 10 years 
                        candidate[2] = 'Senior Manager' 
                    updated_candidates.append(candidate) 
                except EOFError:
                    break  # End of file reached 
    except FileNotFoundError: 
        print("No candidate data found. Please add candidates first.") 
        return 
 
    with open('candidates.bin', 'wb') as file: 
        for candidate in updated_candidates: 
            pickle.dump(candidate, file) 
 
    print("Candidates updated to Senior Manager where applicable.")

update_senior_manager() 

(III)

import pickle 
 
def display_non_senior_managers(): 
    try: 
        with open('candidates.bin', 'rb') as file: 
            while True: 
                try: 
                    candidate = pickle.load(file) 
                    if candidate[2] != 'Senior Manager':  # Check if not Senior Manager 
                        print(f"Candidate ID: {candidate[0]}") 
                        print(f"Candidate Name: {candidate[1]}") 
                        print(f"Designation: {candidate[2]}") 
                        print(f"Experience: {candidate[3]}") 
                        print("--------------------") 
                except EOFError: 
                    break  # End of file reached 
    except FileNotFoundError: 
        print("No candidate data found. Please add candidates first.") 
 
display_non_senior_managers()

Question 37

Event Horizon Enterprises is an event planning organization. It is planning to set up its India campus in Mumbai with its head office in Delhi. The Mumbai campus will have four blocks/buildings - ADMIN, FOOD, MEDIA, DECORATORS. You, as a network expert, need to suggest the best network-related solutions for them to resolve the issues/problems mentioned in points (I) to (V), keeping in mind the distances between various blocks/buildings and other given parameters.

Event Horizon Enterprises is an event planning organization. It is planning to set up its India campus in Mumbai with its head office in Delhi. The Mumbai campus will have four blocks/buildings - ADMIN, FOOD, MEDIA, DECORATORS. CBSE 2025 Computer Science Class 12 Sample Question Paper Solved.

Block to Block distances (in Mtrs.)

FromToDistance
ADMINFOOD42 m
ADMINMEDIA96 m
ADMINDECORATORS48 m
FOODMEDIA58 m
FOODDECORATORS46 m
MEDIADECORATORS42 m

Distance of Delhi Head Office from Mumbai Campus = 1500 km

Number of computers in each of the blocks/Center is as follows:

ADMIN30
FOOD18
MEDIA25
DECORATORS20
DELHI HEAD OFFICE18

(I) Suggest the most appropriate location of the server inside the MUMBAI campus. Justify your choice.

(II) Which hardware device will you suggest to connect all the computers within each building?

(III) Draw the cable layout to efficiently connect various buildings within the MUMBAI campus. Which cable would you suggest for the most efficient data transfer over the network?

(IV) Is there a requirement of a repeater in the given cable layout? Why/ Why not?

(V)

(A) What would be your recommendation for enabling live visual communication between the Admin Office at the Mumbai campus and the DELHI Head Office from the following options:

a) Video Conferencing
b) Email
c) Telephony
d) Instant Messaging

OR

(B) What type of network (PAN, LAN, MAN, or WAN) will be set up among the computers connected in the MUMBAI campus ?

Answer

(I) The most appropriate location for the server inside the MUMBAI campus is ADMIN block because it has maximum number of computers.

(II) Switch is used to connect all the computers within each building.

(III) Cable layout connecting various buildings within the MUMBAI campus is shown below:

Event Horizon Enterprises is an event planning organization. It is planning to set up its India campus in Mumbai with its head office in Delhi. The Mumbai campus will have four blocks/buildings - ADMIN, FOOD, MEDIA, DECORATORS. CBSE 2025 Computer Science Class 12 Sample Question Paper Solved.

For the most efficient data transfer over the network, optical fiber cables are recommended.

(IV) There is no requirement for a repeater as optical fiber cables can transmit signals over longer distances.

(V)

(A) Video Conferencing

Video conferencing is recommended for live communication between the Mumbai and Delhi offices due to its real-time interaction and flexibility making it ideal for effective discussions across distant locations.

OR

(B) The type of network that will be set up among the computers connected in the MUMBAI campus is LAN (Local Area Network).

PrevNext