Back to papers
CBSE · 083Class XII

Computer Science · 2023

30 March 2023 · Main paper

Questions
35
Total marks
70
Sections
5
A

Section A

18 q · 18 marks
01

State True or False. "Identifiers are names used to identify a variable, function in a program".

[1]
Answer

True

Explanation

True. Identifiers are user-defined names for variables, functions, etc.

02

Which of the following is a valid keyword in Python ?

[1]
Answer

(b) return

Explanation

'return' is a reserved keyword in Python. 'false' (should be False), 'non_local' (should be nonlocal), and 'none' (should be None) are incorrect.

03

Given the following Tuple Tup= (10, 20, 30, 50) Which of the following statements will result in an error ?

[1]
Answer

(b) Tup.insert (2,3)

Explanation

Tuples are immutable in Python, so they do not support methods like insert() that modify the collection.

04

Consider the given expression : 5<10 and 12>7 or not 7>4 Which of the following will be the correct output, if the given expression is evaluated ?

[1]
Answer

(a) True

Explanation

5<10 is True, 12>7 is True. 'True and True' is True. 7>4 is True, 'not True' is False. 'True or False' is True.

05

Select the correct output of the code :

python
S = "Amrit Mahotsav @ 75"
A = S.partition(" ")
print(A)
[1]
Answer

(d) ('Amrit','', 'Mahotsav @ 75')

Explanation

str.partition(sep) returns a 3-tuple: (part_before_sep, sep, part_after_sep). Splitting on the first space gives ('Amrit', ' ', 'Mahotsav @ 75'). Note: the original paper printed lowercase 'a' which is an error; CBSE accepted (d) when reading 'A'.

06

Which of the following mode keeps the file offset position at the end of the file ?

[1]
Answer

(d) a

Explanation

The 'a' (append) mode opens a file for writing and positions the file pointer at the end of the file.

07

Fill in the blank. _______ function is used to arrange the elements of a list in ascending order.

[1]
Answer

(a) sort()

Explanation

The sort() method sorts the elements of a list in place. By default, it sorts in ascending order.

08

Which of the following operators will return either True or False ?

[1]
Answer

(b) !=

Explanation

The '!=' (not equal) operator is a comparison operator that returns a boolean value (True or False).

09

Which of the following statement(s) would give an error after executing the following code ? Stud={"Murugan":100, "Mithu":95} # Statement 1 print (Stud[95]) # Statement 2 Stud ["Murugan"]=99 # Statement 3

python
print(Stud.pop()) # Statement 4
print(Stud) # Statement 5
[1]
Answer

(d) Statements 2 and 4

Explanation

Statement 2 fails because 95 is a value, not a key. Statement 4 fails because dict.pop() requires a key argument.

10

Fill in the blank. _______ is a number of tuples in a relation.

[1]
Answer

(d) Cardinality

Explanation

Cardinality refers to the number of rows (tuples) in a relation (table).

11

The syntax of seek( ) is : file_object.seek(offset[,reference_point]) What is the default value of reference_point ?

[1]
Answer

(a) 0

Explanation

The default value for the reference_point in seek() is 0, which represents the beginning of the file.

12

Fill in the blank : _______ clause is used with SELECT statement to display data in a sorted form with respect to a specified column.

[1]
Answer

(b) ORDER BY

Explanation

The ORDER BY clause is used to sort the result set in ascending or descending order.

13

Fill in the blank : _______ is used for point-to-point communication or unicast communication such as radar and satellite.

[1]
Answer

(c) MICROWAVES

Explanation

Microwaves are used for long-distance point-to-point communication like satellite and radar due to their line-of-sight propagation.

14

What will the following expression be evaluated to in Python ? print(4+3*5/3-5%2)

[1]
Answer

(b) 8.0

Explanation

Operator precedence: * and / and % first. 3*5=15, 15/3=5.0, 5%2=1. Then +, -: 4 + 5.0 - 1 = 8.0.

15

Which function returns the sum of all elements of a list ?

[1]
Answer

(b) sum()

Explanation

The built-in sum() function calculates the total of all numeric elements in an iterable like a list.

16

fetchall() method fetches all rows in a result set and returns a :

[1]
Answer

(b) List of tuples

Explanation

The fetchall() method returns all rows from the query result as a list of tuples.

17

Assertion (A) : To use a function from a particular module, we need to import the module. Reason (R) : import statement can be written anywhere in the program, before using a function from that module.

[1]
Answer

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

Explanation

Both statements are true. (A) states a requirement for using modules. (R) is a true syntactic rule but does not explain *why* we must import — so (R) is not the correct explanation for (A).

18

Assertion (A) : A stack is a LIFO structure. Reason (R) : Any new element pushed into the stack always gets positioned at the index after the last existing element in the stack.

[1]
Answer

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

Explanation

Stacks follow LIFO (Last In, First Out). (R) is considered false because a stack is defined abstractly by its 'top'; indices are an implementation detail, not part of the definition. CBSE also accepted (a) and (b) for full marks.

B

Section B

12 q · 20 marks
19

Atharva is a Python programmer working on a program to find and return the maximum value from the list. The code written below has syntactical errors. Rewrite the correct code and underline the corrections made.

python
def max_num (L) :
    max=L(0)
    for a in L :
        if a > max
            max=a
    return max
[2]
Answer
python
def max_num(L):
    max = L[0]          # Correction 1: L[0] instead of L(0)
    for a in L:
        if a > max:     # Correction 2: added colon
            max = a
    return max          # Correction 3: aligned outside the for loop
Explanation

Three corrections: (1) list indexing uses square brackets, so L(0) becomes L[0]; (2) the if statement is missing a colon; (3) return max must be at the function level, not nested inside the for loop.

20(1)

Differentiate between wired and wireless transmission.

[2]
Answer

Wired transmission uses physical cables (guided media) like twisted pair or fiber optics. Wireless transmission uses electromagnetic waves (unguided media) like radio waves or microwaves to transmit data through air/vacuum.

Explanation

Wired is guided, Wireless is unguided.

20(2)

Differentiate between URL and domain name with the help of an appropriate example.

[2]
Answer

URL (Uniform Resource Locator) is the complete address of a resource on the web (e.g., https://www.google.com/search). A Domain Name is just the human-readable address of the website's server (e.g., google.com), which is a part of the URL.

Explanation

URL includes protocol, path etc. Domain is the site identifier.

21(1)

Given is a Python list declaration : Listofnames=["Aman","Ankit","Ashish","Rajan","Rajat"] Write the output of : print (Listofnames [-1:-4:-1])

[1]
Answer

['Rajat', 'Rajan', 'Ashish']

Explanation

Slicing [-1:-4:-1] starts at the last element, moves backwards, and stops before the 4th element from the end.

21(2)

Consider the following tuple declaration : tupl=(10,20,30,(10,20,30),40) Write the output of : print(tupl.index(20))

[1]
Answer

1

Explanation

The index() method returns the index of the first occurrence of the value 20, which is at index 1.

22

Explain the concept of "Alternate Key" in a Relational Database Management System with an appropriate example.

[2]
Answer

An Alternate Key is any Candidate Key that is not chosen to be the Primary Key. For example, in a Student table with Candidate Keys {AdmNo, RollNo}, if AdmNo is the Primary Key, then RollNo is the Alternate Key.

Explanation

It's a candidate key not selected as primary.

23(1)

Write the full forms of the following : (i) HTML (ii) TCP

[1]
Answer

(i) Hyper Text Markup Language (ii) Transmission Control Protocol

Explanation

Standard technical acronyms.

23(2)

What is the need of Protocols ?

[1]
Answer

Protocols are standard rules that govern data communication, ensuring that different devices can interpret signals correctly. Without protocols, devices would not be able to exchange information reliably.

Explanation

Rules for communication/compatibility.

24(1)

Write the output of the code given below :

python
def short_sub(lst, n):
    for i in range(0, n):
        if len(lst) > 4:
            lst[i] = lst[i] + lst[i]
        else:
            lst[i] = lst[i]

subject = ['CS', 'HINDI', 'PHYSICS', 'CHEMISTRY', 'MATHS']
short_sub(subject, 5)
print(subject)
[2]
Answer
text
['CSCS', 'HINDIHINDI', 'PHYSICSPHYSICS', 'CHEMISTRYCHEMISTRY', 'MATHSMATHS']
Explanation

The list has 5 elements, so len(lst) > 4 is always True. Each element at indices 0–4 is replaced with itself concatenated with itself.

24(2)

Write the output of the code given below :

python
a = 30
def call(x):
    global a
    if a % 2 == 0:
        x += a
    else:
        x -= a
    return x

x = 20
print(call(35), end="#")
print(call(40), end="@")
[2]
Answer
text
65#70@
Explanation

a = 30 is even, so x += a is taken in both calls. First call: 35 + 30 = 65, printed with '#'. Second call: 40 + 30 = 70, printed with '@'.

25(1)

Differentiate between CHAR and VARCHAR data types in SQL with appropriate example.

[2]
Answer

CHAR is a fixed-length string type. Declaring CHAR(10) always reserves space for 10 characters; shorter values are padded with spaces on the right.

VARCHAR is a variable-length string type. Declaring VARCHAR(30) allows up to 30 characters but only uses the bytes needed for the actual data.

Example: To store 'India' — CHAR(20) occupies 20 bytes, whereas VARCHAR(20) occupies only about 5 bytes.

Explanation

CHAR uses fixed storage with padding; VARCHAR uses only the storage required by the actual value.

25(2)

Name any two DDL and any two DML commands.

[2]
Answer

DDL (any two): CREATE, ALTER, DROP

DML (any two): INSERT, UPDATE, DELETE, SELECT

Explanation

DDL (Data Definition Language) defines or alters database schema; DML (Data Manipulation Language) reads and modifies the data within tables.

C

Section C

9 q · 24 marks
26(1)

Consider the following tables – LOAN and BORROWER :

Table : LOAN

LOAN_NOB_NAMEAMOUNT
L-170DELHI3000
L-230KANPUR4000

Table : BORROWER

CUST_NAMELOAN_NO
JOHNL-171
KRISHL-230
RAVYAL-170

How many rows and columns will be there in the natural join of these two tables ?

[3]
Answer

Rows : 2

Columns : 4

Explanation

Natural join matches rows on the common attribute LOAN_NO. L-170 and L-230 match in both tables (2 rows); L-171 has no match. Columns = (LOAN_NO, B_NAME, AMOUNT, CUST_NAME) — the shared LOAN_NO appears only once.

26(2)

Write the output of the queries (i) to (iv) based on the table, WORKER given below :

Table : WORKER

W_IDF_NAMEL_NAMECITYSTATE
102SAHILKHANKANPURUTTAR PRADESH
104SAMEERPARIKHROOP NAGARPUNJAB
105MARYJONESDELHIDELHI
106MAHIRSHARMASONIPATHARYANA
107ATHARVABHARDWAJDELHIDELHI
108VEDASHARMAKANPURUTTAR PRADESH

(i) SELECT F_NAME, CITY FROM WORKER ORDER BY STATE DESC; (ii) SELECT DISTINCT(CITY) FROM WORKER; (iii) SELECT F_NAME, STATE FROM WORKER WHERE L_NAME LIKE '_HA%'; (iv) SELECT CITY, COUNT(*) FROM WORKER GROUP BY CITY;

[3]
Answer

(i)

F_NAMECITY
SAHILKANPUR
VEDAKANPUR
SAMEERROOP NAGAR
MAHIRSONIPAT
MARYDELHI
ATHARVADELHI

(ii)

CITY
KANPUR
ROOP NAGAR
DELHI
SONIPAT

(iii)

F_NAMESTATE
SAHILUTTAR PRADESH
MAHIRHARYANA
ATHARVADELHI
VEDAUTTAR PRADESH

(iv)

CITYCOUNT(*)
KANPUR2
ROOP NAGAR1
DELHI2
SONIPAT1
Explanation

(i) Sorted by STATE in descending order. (ii) DISTINCT removes duplicate city entries. (iii) The pattern '_HA%' matches names with any first char then 'HA' (KHAN, SHARMA, BHARDWAJ). (iv) Counts workers grouped by city.

27(1)

Write the definition of a Python function named LongLines() which reads the contents of a text file named 'LINES.TXT' and displays those lines from the file which have at least 10 words in it.

For example, if the content of 'LINES.TXT' is :

text
Once upon a time, there was a woodcutter
He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.

Then the function should display :

text
He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.
[3]
Answer
python
def LongLines():
    with open('LINES.TXT', 'r') as myfile:
        for line in myfile:
            if len(line.split()) >= 10:
                print(line)
Explanation

Opens the file, iterates line by line, splits each line on whitespace to get a word list, and prints lines whose word count is at least 10.

27(2)

Write a function count_Dwords() in Python to count the words ending with a digit in a text file "Details.txt".

Example: If the file content is :

text
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting

The output should be :

text
Number of words ending with a digit are 4
[3]
Answer
python
def count_Dwords():
    count = 0
    with open("Details.txt", 'r') as F:
        S = F.read()
        Wlist = S.split()
        for W in Wlist:
            if W[-1].isdigit():
                count += 1
    print("Number of words ending with a digit are", count)
Explanation

Reads the file, splits the contents into words on whitespace, and checks the last character of each word with isdigit().

28(1)

Write the outputs of the SQL queries (i) to (iv) based on the relations COMPUTER and SALES given below :

Table : COMPUTER

PROD_IDPROD_NAMEPRICECOMPANYTYPE
P001MOUSE200LOGITECHINPUT
P002LASER PRINTER4000CANONOUTPUT
P003KEYBOARD500LOGITECHINPUT
P004JOYSTICK1000IBALLINPUT
P005SPEAKER1200CREATIVEOUTPUT
P006DESKJET PRINTER4300CANONOUTPUT

Table : SALES

PROD_IDQTY_SOLDQUARTER
P00241
P00322
P00132
P00421

(i) SELECT MIN(PRICE), MAX(PRICE) FROM COMPUTER; (ii) SELECT COMPANY, COUNT(*) FROM COMPUTER GROUP BY COMPANY HAVING COUNT(COMPANY) > 1; (iii) SELECT PROD_NAME, QTY_SOLD FROM COMPUTER C, SALES S WHERE C.PROD_ID = S.PROD_ID AND TYPE = 'INPUT'; (iv) SELECT PROD_NAME, COMPANY, QUARTER FROM COMPUTER C, SALES S WHERE C.PROD_ID = S.PROD_ID;

[2]
Answer

(i)

MIN(PRICE)MAX(PRICE)
2004300

(ii)

COMPANYCOUNT(*)
LOGITECH2
CANON2

(iii)

PROD_NAMEQTY_SOLD
MOUSE3
KEYBOARD2
JOYSTICK2

(iv)

PROD_NAMECOMPANYQUARTER
MOUSELOGITECH2
LASER PRINTERCANON1
KEYBOARDLOGITECH2
JOYSTICKIBALL1
Explanation

(i) MIN and MAX of PRICE. (ii) Groups by COMPANY and keeps only groups with more than 1 row. (iii) Joins on PROD_ID and filters INPUT-type products. (iv) Full equi-join on PROD_ID.

28(2)

Write the command to view all databases.

[1]
Answer

SHOW DATABASES;

Explanation

Standard MySQL command to list available databases.

29

Write a function EOReplace() in Python, which accepts a list L of numbers. Thereafter, it increments all even numbers by 1 and decrements all odd numbers by 1.

Example : If the input list is :

python
L = [10, 20, 30, 40, 35, 55]

The output will be :

python
L = [11, 21, 31, 41, 34, 54]
[3]
Answer
python
def EOReplace(L):
    for i in range(len(L)):
        if L[i] % 2 == 0:
            L[i] = L[i] + 1
        else:
            L[i] = L[i] - 1
    print(L)
Explanation

Iterates the list by index. Even values are incremented by 1, odd values are decremented by 1. Modifying by index updates the list in place.

30(1)

A list contains the following record of a customer : [Customer_name, Room_Type]

Write the following user defined functions to perform given operations on the stack named 'Hotel' :

(i) Push_Cust() – To Push customers' names of those customers who are staying in 'Delux' Room Type. (ii) Pop_Cust() – To Pop the names of customers from the stack and display them. Also, display "Underflow" when there are no customers in the stack.

For example, if the lists with customer details are :

python
["Siddharth", "Delux"]
["Rahul", "Standard"]
["Jerry", "Delux"]

The stack should contain : Jerry, Siddharth

And the output of Pop_Cust() should be :

text
Jerry
Siddharth
Underflow
[3]
Answer
python
Hotel = []
Customer = [["Siddharth", "Delux"], ["Rahul", "Standard"], ["Jerry", "Delux"]]

def Push_Cust():
    for rec in Customer:
        if rec[1] == "Delux":
            Hotel.append(rec[0])

def Pop_Cust():
    while len(Hotel) > 0:
        print(Hotel.pop())
    else:
        print("Underflow")
Explanation

Push_Cust filters customer records by Room_Type and appends matching names. Pop_Cust pops and prints until the stack is empty, then displays 'Underflow'.

30(2)

Write a function in Python, Push(Vehicle) where Vehicle is a dictionary containing details of vehicles — {Car_Name: Maker}. The function should push the name of every car manufactured by 'TATA' (in any case — Tata, TaTa, etc.) onto the stack.

For example, if the dictionary contains :

python
Vehicle = {"Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}

The stack should contain : Safari, Nexon

[3]
Answer
python
stack = []

def Push(Vehicle):
    for v_name in Vehicle:
        if Vehicle[v_name].upper() == "TATA":
            stack.append(v_name)
Explanation

Iterates over the dictionary keys, normalises each value with .upper(), and appends qualifying keys to the stack.

D

Section D

9 q · 15 marks
31(1)

Quickdev, an IT-based firm located in Delhi, is planning to set up a network for its four branches within the city with its Marketing department in Kanpur. As a network professional, give solutions to the questions (i) to (v), after going through the branches locations and other details which are given below:

Distance between various branches is as follows :

BranchDistance
Branch A to Branch B40 m
Branch A to Branch C80 m
Branch A to Branch D65 m
Branch B to Branch C30 m
Branch B to Branch D35 m
Branch C to Branch D15 m
Delhi Branch to Kanpur300 km

Number of computers in each of the branches :

BranchNumber of Computers
Branch A15
Branch B25
Branch C40
Branch D115

(i) Suggest the most suitable place to install the server for the Delhi branch with a suitable reason.

[1]
Answer

Branch D — it has the maximum number of computers.

Explanation

Placing the server at the branch with the largest number of clients minimises overall network traffic and cabling cost. (Any other branch with valid justification is also acceptable.)

31(2)

(ii) Suggest an ideal layout for connecting all these branches within Delhi.

[1]
Answer

Star Topology

Explanation

Ideally connected to the server at Branch D.

31(3)

(iii) Which device will you suggest, that should be placed in each of these branches to efficiently connect all the computers within these branches ?

[1]
Answer

Switch (or Hub / Router)

Explanation

A switch (or hub) connects multiple devices within a single LAN segment so they can communicate with each other.

31(4)

(iv) Delhi firm is planning to connect to its Marketing department in Kanpur which is approximately 300 km away. Which type of network out of LAN, WAN or MAN will be formed ? Justify your answer.

[1]
Answer

WAN (Wide Area Network) — because the network spans different geographical locations of the country (approx. 300 km apart).

Explanation

A WAN connects sites separated by large distances; LANs cover a single building/campus and MANs cover a city. 300 km between Delhi and Kanpur places this beyond both.

31(5)

(v) Suggest a protocol that shall be needed to provide help for transferring of files between Delhi and Kanpur branch.

[1]
Answer

FTP (File Transfer Protocol)

Explanation

FTP is the standard protocol for transferring files over a network.

32(1)

What possible output(s) are expected to be displayed on screen at the time of execution of the following program ?

python
import random
M = [5, 10, 15, 20, 25, 30]
for i in range(1, 3):
    first = random.randint(2, 5) - 1
    sec = random.randint(3, 6) - 2
    third = random.randint(1, 4)
    print(M[first], M[sec], M[third], sep="#")
[2]
Answer

(a) 10#25#15 20#25#25

Explanation

random.randint(2,5)-1 yields indices in {1,2,3,4}; random.randint(3,6)-2 yields {1,2,3,4}; random.randint(1,4) yields {1,2,3,4}. All three subscripts are always valid (1..4) and the separator '#' has no trailing '#' at the end of each line. Only option (a) satisfies these constraints on both iterations.

32(1or)

Predict the output of the code given below :

python
def makenew(mystr):
    newstr = ""
    count = 0
    for i in mystr:
        if count % 2 != 0:
            newstr = newstr + str(count)
        else:
            if i.lower():
                newstr = newstr + i.upper()
            else:
                newstr = newstr + i
        count += 1
    print(newstr)

makenew("No@1")
[2]
Answer
text
N1@3
Explanation

Trace by character of "No@1": - count=0 (even): 'N' → upper → 'N'. newstr="N" - count=1 (odd): append str(1) → '1'. newstr="N1" - count=2 (even): '@'.lower() is truthy → upper → '@'. newstr="N1@" - count=3 (odd): append str(3) → '3'. newstr="N1@3"

32(2)

The code given below deletes the record from the table employee which has the structure :

text
E_code  - String
E_name  - String
Sal     - Integer
City    - String

Note: Username is root, Password is root, the table exists in MySQL database named emp.

Write the following statements to complete the code : - Statement 1 — to import the desired library. - Statement 2 — to execute the command that deletes the record with E_code as 'E101'. - Statement 3 — to delete the record permanently from the database.

python
import __________ as mysql        # Statement 1

def delete():
    mydb = mysql.connect(host="localhost", user="root",
                         passwd="root", database="emp")
    mycursor = mydb.cursor()
    __________________            # Statement 2
    __________________            # Statement 3
    print("Record deleted")
[3]
Answer
python
import mysql.connector as mysql                                          # Statement 1

mycursor.execute("DELETE FROM employee WHERE E_code='E101'")             # Statement 2
mydb.commit()                                                            # Statement 3
Explanation

Statement 1 imports the MySQL connector. Statement 2 executes the DELETE query through the cursor. Statement 3 commits the transaction so the deletion is permanent.

32(2or)

The code given below reads the records from the table employee and displays only those whose city is 'Delhi'. The table has the structure :

text
E_code  - String
E_name  - String
Sal     - Integer
City    - String

Note: Username is root, Password is root, MySQL database is named emp.

Write the following statements to complete the code : - Statement 1 — to import the desired library. - Statement 2 — to execute the query that fetches records of employees from city 'Delhi'. - Statement 3 — to read the complete data of the query into the object named details.

python
import __________ as mysql        # Statement 1

def display():
    mydb = mysql.connect(host="localhost", user="root",
                         passwd="root", database="emp")
    mycursor = mydb.cursor()
    __________________            # Statement 2
    details = ________            # Statement 3
    for i in details:
        print(i)
[3]
Answer
python
import mysql.connector as mysql                                          # Statement 1

mycursor.execute("SELECT * FROM employee WHERE City='Delhi'")            # Statement 2
details = mycursor.fetchall()                                            # Statement 3
Explanation

Statement 1 imports the MySQL connector. Statement 2 runs a SELECT filtered by City='Delhi'. Statement 3 retrieves all matching rows from the cursor via fetchall().

E

Section E

8 q · 22 marks
33(1)

Write one difference between CSV and text files. Write a program in Python that defines and calls the following user defined functions :

(i) COURIER_ADD() — It takes the values from the user and adds the details to a csv file 'courier.csv'. Each record consists of a list with field elements cid, s_name, Source, destination to store Courier ID, Sender name, Source and Destination address respectively.

(ii) COURIER_SEARCH() — Takes the destination as input and displays all the courier records going to that destination.

[5]
Answer

Difference between CSV and Text files : - CSV files can be viewed in spreadsheets and require the csv module to be imported; text files can be viewed in a text editor and need no special module. - CSV files store records as comma-separated values; text files store free-form text.

python
import csv

def COURIER_ADD():
    f1 = open("courier.csv", "a", newline="")
    writ = csv.writer(f1)
    cid = int(input("Enter the Courier id: "))
    s_name = input("Enter the Sender Name: ")
    Source = input("Enter the Source Address: ")
    destination = input("Enter Destination Name: ")
    detail = [cid, s_name, Source, destination]
    writ.writerow(detail)
    f1.close()

def COURIER_SEARCH():
    f1 = open("courier.csv", "r")
    detail = csv.reader(f1)
    name = input("Enter the Destination Name to be searched: ")
    for i in detail:
        if i[3] == name:
            print("Details of courier are: ", i)
    f1.close()

COURIER_ADD()
COURIER_SEARCH()
Explanation

COURIER_ADD opens the CSV in append mode and writes a list of fields with csv.writer. COURIER_SEARCH iterates rows using csv.reader and matches index 3 (destination) against the user's input.

33(2)

Why is it important to close a file before exiting ? Write a program in Python that defines and calls the following user defined functions :

(i) Add_Book() — Takes the details of the books and adds them to a csv file 'Book.csv'. Each record consists of a list with field elements book_ID, B_name, pub to store book ID, book name and publisher respectively.

(ii) Search_Book() — Takes the publisher name as input and counts and displays the number of books published by them.

[5]
Answer

Why close a file ? It is important to close a file before exiting so that any unwritten or buffered data is flushed to disk and the system resources held by the file (file descriptor, memory buffers) are released back to the OS.

python
import csv

def Add_Book():
    f1 = open("Book.csv", "a", newline="")
    writ = csv.writer(f1)
    book_ID = int(input("Enter the Book id: "))
    B_name = input("Enter the Book Name: ")
    pub = input("Enter the Publisher Name: ")
    detail = [book_ID, B_name, pub]
    writ.writerow(detail)
    f1.close()

def Search_Book():
    f1 = open("Book.csv", "r")
    detail = csv.reader(f1)
    name = input("Enter the Publisher Name to be searched: ")
    pub_count = 0
    for i in detail:
        if i[2] == name:
            pub_count += 1
    print("NUMBER OF BOOKS: ", pub_count)
    f1.close()

Add_Book()
Search_Book()
Explanation

Add_Book opens 'Book.csv' in append mode and writes a single row. Search_Book reads each row and increments a counter whenever index 2 (publisher) matches the input.

34(1)

The school has asked their estate manager Mr. Rahul to maintain the data of all the labs in a table LAB. Rahul has created the table and entered data of 5 labs.

Table : LAB

LABNOLAB_NAMEINCHARGECAPACITYFLOOR
L001COMPUTERVIJAY30II
L002CHEMISTRYHARSH20I
L003BIOLOGYSONIA20I
L004ENGLISHGAGAN40II
L005MATHSMEENU35III

(i) Identify the columns which can be considered as Candidate keys.

[1]
Answer

Candidate keys : LABNO and LAB_NAME

Explanation

Both LABNO and LAB_NAME contain unique, non-null values for every row, so either could serve as the primary key — that makes both candidate keys.

34(2)

(ii) Write the degree and cardinality of the table LAB.

[1]
Answer

Degree = 5

Cardinality = 5

Explanation

Degree is the number of attributes (columns): LABNO, LAB_NAME, INCHARGE, CAPACITY, FLOOR → 5. Cardinality is the number of tuples (rows) → 5.

34(3)

(iii) Write the statements to : (a) Insert a new row with appropriate data. (b) Increase the capacity of all the labs by 10 students which are on 'I' Floor.

[2]
Answer

(a)

sql
INSERT INTO LAB VALUES('L006', 'PHYSICS', 'RAVI', 25, 'II');

(b)

sql
UPDATE LAB SET CAPACITY = CAPACITY + 10 WHERE FLOOR = 'I';
Explanation

(a) INSERT INTO ... VALUES adds a new tuple supplying values for every column in declared order. (b) UPDATE with a WHERE clause modifies only rows whose FLOOR is 'I', incrementing CAPACITY by 10.

34(3or)

(iii) Write the statements to : (a) Add a constraint PRIMARY KEY to the column LABNO in the table LAB. (b) Delete the table LAB.

[2]
Answer

(a)

sql
ALTER TABLE LAB ADD PRIMARY KEY (LABNO);

(b)

sql
DROP TABLE LAB;
Explanation

(a) ALTER TABLE ... ADD PRIMARY KEY attaches a primary-key constraint to an existing column. (b) DROP TABLE removes both the table structure and its data permanently.

35(1)

Shreyas is a programmer who has been given the task of writing a function write_bin() to create a binary file Cust_file.dat containing customer records — customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt).

The function accepts c_no, c_name, qty and price. If qty is less than 10, it prints 'Quantity less than 10 ..... Cannot SAVE'. Otherwise it computes amt = price * qty and writes the record (as a list) to the binary file.

python
import pickle

def write_bin():
    bin_file = __________              # Statement 1
    while True:
        c_no = int(input("enter customer number"))
        c_name = input("enter customer name")
        qty = int(input("enter qty"))
        price = int(input("enter price"))
        if __________ :                # Statement 2
            print("Quantity less than 10..Cannot SAVE")
        else:
            amt = price * qty
            c_detail = [c_no, c_name, qty, price, amt]
            __________                 # Statement 3
            ans = input("Do you wish to enter more records y/n")
            if ans.lower() == 'n':
                __________             # Statement 4
    ______________                     # Statement 5

______________                         # Statement 6

Answer the following : (i) Write the correct Statement 1 to open 'Cust_file.dat' for writing. (ii) Write Statement 2 to check whether qty is less than 10. (iii) Write Statement 3 to write data to the binary file and Statement 4 to stop further processing if the user does not wish to enter more records.

[4]
Answer

(i) Statement 1

python
bin_file = open("Cust_file.dat", "wb")

("ab" mode is also accepted.)

(ii) Statement 2

python
qty < 10

(iii) Statement 3

python
pickle.dump(c_detail, bin_file)

Statement 4

python
break
Explanation

Statement 1 opens the file in binary-write mode. Statement 2 is the condition that flags a too-small quantity. Statement 3 serialises the record list to the binary file with pickle.dump. Statement 4 exits the while loop when the user has no more records to enter.

35(2)

(iii) (Option only for part (iii))

What should Shreyas fill in : - Statement 5 to close the binary file named Cust_file.dat ? - Statement 6 to call the function write_bin() that writes data to the binary file ?

(Refer to the code template given in part (i) of question 35.)

[2]
Answer

Statement 5

python
bin_file.close()

Statement 6

python
write_bin()
Explanation

Statement 5 releases the file resource, flushing any buffered bytes to disk. Statement 6 actually invokes the function so the file is created and populated.

End of paper
Source · CBSE Class XII Computer Science (083) · 2023