You are on page 1of 92

Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 1 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. A device that connects two dissimilar networks is


Section A (a) modem (b) repeater
(c) bridge (d) gateway
1. The output of the code will be :
Sol :
s=“Wonders of World”
print(s.count(‘O’) + s.index(‘o’)) (d) Gateway
(a) 3 (b) 4
(c) 2 (d) 1 6. In which file, no delimiters are used for line and
no translations occur?
Sol : (a) Text file (b) Binary file
(b) 4 (c) CSV file (d) None of these
Sol :
2. The constraint that is used to provide a condition
on a field to take specific values only is : (b) Binary file
(a) NULL (b) PRIMARY KEY
(c) CHECK (d) NOT NULL 7. State True or False
“Multiple elements can be added at the end of list
Sol : by the append method”.
(c) CHECK Sol :
3. Which of the following are random number False
generators ?
(a) randint() (b) randrange() 8. These operators are used to make a decision on
(c) random() (d) All of these two conditions.
(a) Logical (b) Arithmetic
Sol : (c) Relational (d) Assignment
(d) All of these Sol :
4. Which of the following are sequence of character (a) Logical
data?
(a) Lists 9. In files, there is a key associated with each record
(b) Tuples which is used to differentiate among different
(c) Strings records. For every file, there is atleast one set of
(d) Dictionaries keys that is unique. Such a key is called
(a) unique key (b) prime attribute
Sol : (c) index key (d) primary key
(c) Strings Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(d) primary key 15. The........keyword sorts the records in ascending


order by default.
10. a = 1.0 (a) LIKE
b = 1.0 (b) UPDATE
a is b # Line 1 (c) ORDER
Output of Line 1 will be (d) ORDER BY
(a) False (b) True
(c) 1.0 (d) 0.0 Sol :

Sol : (d) ORDER BY

(a) False 16. .........method takes a string and writes it in the


file.
11. Which of the following is a correct syntax to add (a) writelines()
a column in SQL command? (b) write()
(a) ALTER TABLE table_name ADD column_ (c) writerow()
name data_type; (d) writer()
(b) ALTER TABLE ADD column_name data_
type; Sol :
(c) ALTER table_name ADD column_name (b) write()
data_type;
(d) None of the above Directions : (Q.Nos.-17 and 18) are Assertion and
Reason based Questions.
Sol :
(a) ALTER TABLE table_name ADD column_ 17. Assertion (A) Built-in functions are predefined
name data_type; in the system and can be directly used in any
program.
12. In complex number a + ib, a represents as Reason (R) id( ) and type( ) are built-in functions
(a) real part in Python.
(b) imaginary part (a) Both A and R are true and R is the correct
(c) special part explanation for A.
(d) None of these (b) Both A and R are true but R is not the
Sol : correct explanation for A.
(c) A is true but R is false.
(a) real part
(d) A is false but R is true.
13. a = 6
b = 5.5 Sol :
sum = a+b (b) Both A and R are true but R is not the correct
print(sum) explanation for A.
print(type (sum))
(a) 11.5 (b) 10.5 18. Assertion (A) The CSV files are like TEXT files
<class ‘float’> <class ‘float’> and are comma separated value files.
(c) None (d) None of these Reason (R) The data stored in CSV files are
<class ‘int’> separated by comma by default. Although the
delimiter can be changed.
Sol : (a) Both A and R are true and R is the correct
(a) 11.5 explanation for A.
<class ‘float’> (b) Both A and R are true but R is not the
correct explanation for A.
14. A column storing Name of a department in a (c) A is true but R is false.
table Emp will be of type (d) A is false but R is true.
(a) int (b) date
(c) float (d) varchar Sol :
(a) Both A and R are true and R is the correct
Sol :
explanation for A.
(d) varchar
Page 3 Sample Paper 1 Computer Science Class 12

Section - B 21. Observe the code and write the output


(a) ‘arihant publication’.
19. Riya was asked to accept a list of even numbers
count(‘hant’, 0, 10)
(b) dic = {}
,but she did not put the relevant condition while
accepting the list of numbers. She wrote a user
dic [(1, 2, 4)] = 8
defined function odd to even (L) that accepts the
dic [(4, 2, 1)] = 10
list L as an argument and converts all the odd
dic [1, 2)] = 24
numbers into even by multiplying them by 2.
sum = 0
for i in dic :
def oddtoeven (L)
sum = sum + dic[i]
for i in range (size(L)):
print (sum)
if (L[i]%2! == 0)
L[i]= L[1] ** 2 Sol :
print (L) (a) 1 (b) 42
There are some errors in the code . Rewrite the
correct code. 22. Write about the terms degree and cardinality of
Sol : a table.

def oddtoeven (L) Sol :


for i in range (len(L)): Degree It refers to the number of columns/
if (L[i]%2! = 0): attributes in a table.
L[i]= L[i]*2 Cardinality It refers to the number of rows/
print (L) records in a table.
A table Employee stores records of 10 employees
20. How are E-mail and chat applications different? in the following structure
Sol : Eno Ename Dept Salary
The degree of the table is 4.
E-mail Chat The cardinality of the table is 10.

E-mail or Electronic A chat is a kind of 23. (a) Write the full forms of
mail is a system where application that needs (i) URL
the recipient may not both the users to be (ii) VoIP
be online. online in real time. (b) Write the use of SMTP.
Sol :
The sender writes an Each writes a message
(a) (i) URL Uniform Resource Locator
E-mail address, subject and sends it to other.
and the message along On the other side (ii) VoIP Voice over Internet Protocol
with any attachment the receiver reads (b) SMTP (Simple Mail Transfer Protocol) is
files and sends. the message and a protocol used for sending and receiving
accordingly answers. emails.

or
24. Find the output of following code.
How are LAN and MAN different? dic = {“Nitin” : (21, “NIIT”), “Ankit”
Sol : : (15, “NIIT”)}
print(“The original dictionary : ”,
LAN (Local Area Network) is a kind of network of str(dic))
computers within a local area like a room, campus result= [(key, i, j) for key, (i, j)
, building etc. The computers may be connected in dic.items()]
by wires or wireless mediums . Distance is roughly print(“The list after conversion :
500 m – 1 km. MAN (Metropolitan Area Network) ”, str(result))
is a kind of network of computers spread across a
city. The range is roughly the diameter of a city – Sol :
60 Km . CATTV is an example of MAN. The original dictionary : {‘Ankit’ : (15,
‘NIIT’), ‘Nitin’ : (21, ‘NIIT’)}
Page 4 Sample Paper 1 Computer Science Class 12

The list after conversion : [(‘Ankit’, 15, Section-C


‘NIIT’), (‘Nitin’, 21, ‘NIIT’)]
or
What output will be generate when the following 26. (a) Consider the following tables - STUDENT
Python code is executed? and STREAM :
def ChangeList ():
TABLE: STUDENT
l =[]
l1=[] SCODE NAME AGE STRCDE POINTS GRADE
l2=[] 101 Amit 16 1 6 NULL
for i in range(1, 10): 102 Arjun 13 3 4 NULL
l.append(i)
103 Zaheer 14 2 1 NULL
for i in range(10, 1, –2):
l1.append(i)
for i in range(len (l1)): TABLE: STREAM
l2.append(l1[i] + l[i]) STRCDE STRNAME
l2.append (len(l)– len(l1))
print(l2) 1 SCIENCE+COMP
ChangeList() 2 SCIENCE+ BIO
Sol : 3 SCIENCE+ECO
Output 4 COMMERCE+MATHS
[11, 10, 9, 8, 7, 4]
What will be the ouput of the following statement?
25. Differentiate between DROP and DELETE SELECT NAME, STRNAME FROM STUDENT S,
commands of SQL. STREAM ST WHERE S.STRCDE=ST.STRCDE;

Sol :
(b) Write the output for SQL queries (i) to (iv),
DROP A DDL command is used to remove a table
which are based on the table ITEMS.
or a database. The DROP command removes the
entire table with its structure and records. TABLE: ITEMS
DELETE A DML command is used to delete Code IName Qty Price Company TCode
records of a table. 1001 DIGITAL 120 11000 XENITA T01
or PAD 12i
Identify any two DML commands from the 1006 LED 70 38000 SANTORA T02
following and also explain. SCREEN
ALTER , INSERT , UPDATE , DROP , CREATE 40

Sol : 1004 CAR GPS 50 2150 GEOKNOW T01


SYSTEM
INSERT UPDATE 1003 DIGITAL 160 8000 DIGICLICK T02
The INSERT command adds a record to a table. CAMERA
The UPDATE command is used to change 12X
record(s) of a table. 1005 PEN 600 1200 STOREHOME T03
DRIVE 32
GB

(i) SELECT MAX(Price), MIN(Price)


FROM ITEMS;
(ii) SELECT Price * Qty AS AMOUNT
FROM ITEMS WHERE Code=1004;
(iii) SELECT DISTINCT TCode FROM ITEMS;
(iv) SELECT MAX(Company) FROM ITEMS
WHERE Price > 7000;
Sol :
(a)
Page 5 Sample Paper 1 Computer Science Class 12

print(“U :”.u)
NAME STRNAME
f.close()
Amit SCIENCE + COMP or
Arjun SCIENCE + ECO Write a Python program to find the longest word
in file “status.txt”. If contents of status.txt are
Zaheer SCIENCE + BIO Welcome to your one-step solutions for all your
(b) (i) study, practice and assessment need for various
MAX(Price) MIN(Price) competitive and recruitment examinations and
school segment. We have been working tirelessly
38000 1200
for over a decade to make sure that you have
(ii)
best in class study resources because you deserve
AMOUNT SUCCESS AND NOTHING LESS...
107500 Output should be
(iii) Longest word : examinations
TCode Sol :
T01 def Longest():
f=open(“status.txt”)
T02
words=f.read().split()
T03 max_len=len(max(words, key=len))
(iv) for word in words:
MAX (Company) if(len(word)==max_len):
print(“Longest word:”,word)
XENITA

27. Write a function countEU() in Python, which 28. (a) Consider the following tables GARMENT
should read each character of a text file. IMP. and FABRIC. Write SQL commands for the
TXT should count and display the occurrence of statements (i) to (iv).
alphabets E and U (including small cases e and
TABLE: GARMENT
u too).
e.g. If the file content is as follows : GCODE DESCRI- PRICE FCODE READY-
PTION DATE
Pinaky has gone to his friend’s house.
His friend’s name is Ravya. Her house is 12 km 10023 PENCIL 1150 F03 19-DEC-08
SKIRT
from Pinaky’s house.
The countEU() function should display the 10001 FORMAL 1250 F01 12-JAN-08
SHIRT
output as
E:8 10012 INFORMAL 1550 F02 06-JUN-08
SHIRT
U:3
10024 BABY TOP 750 F03 07-APR-07
Sol :
10090 TULIP 850 F02 31-MAR-07
def countEU(): SKIRT
f=open(“IMP.TXT”) 10019 EVENING 850 F03 06-JUN-08
e=0 GOWN
u=0 10009 INFORMAL 1500 F02 20-OCT-08
while True: PANT
l=f.readline() 10007 FORMAL 1350 F01 09-MAR-08
if not l: PANT
break 10020 FROCK 850 F04 09-SEP-07
for i in l: 10089 SLACKS 750 F03 20-OCT-08
if(i==‘E’ or i==‘e’):
e=e+1
elif(i==‘U’ or i==‘u’): TABLE: FABRIC
u=u+1 FCODE TYPE
print(“E :”,e) F04 POLYSTER
Page 6 Sample Paper 1 Computer Science Class 12

print (x[i]*2)
F02 COTTON
F03 SILK 30. Julie has created a dictionary containing names
and marks as key value pairs of 6 students. Write
F01 TERELENE
a program, with separate user defined functions
(i) To display GCODE and DESCRIPTION to perform the following operations
of each GARMENT in descending order (a) Push the keys (name of the student) of
of GCODE. the dictionary into a stack, where the
(ii) To display the details of all the corresponding value (marks) is greater than
GARMENTs, which have READYDATE 75.
in between 08-DEC-07 and 16-JUN-08 (b) Pop and display the content of the stack.
(inclusive of both the dates). For example If the sample content of the dictionary
(iii) To display the average PRICE of all the is as follows
GARMENTs. Which are made up of R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”:65,
FABRIC with FCODE as F03. “ANU”:90, “TOM”:82}
(iv) To display FABRIC wise highest and The output from the program should be
lowest price of GARMENTs from TOM ANU BOB OM
GARMENT table.
Sol :
(Display FCODE of each GARMENT
alongwith highest and lowest price.) R={“OM”:76, “JAI”:45, “BOB”:89,
(b) Write a command to remove all the records of “ALI”: 65, “ANU”:90, “TOM”:82}
a table “Shipping”. def PUSH(S,N):
S.append(N)
Sol :
def POP(S):
(a) (i) SELECT GCODE, DESCRIPTION FROM if S!-[]:
GARMENT ORDER BY GCODE DESC; return S.pop()
(ii) SELECT*FROM GARMENT else:
WHERE READYDATE BETWEEN ‘08- return None
DEC-07’ AND ‘16-JUN-08’; ST=[ ]
(iii) SELECT AVG(PRICE) FROM GARMENT for k in R:
WHERE FCODE — ‘F03’; if R[k]>=75:
(iv) SELECT FCODE, MAX(PRICE), PUSH(ST, k)
MIN(PRICE) FROM GARMENT GROUP while True:
BY FCODE; if ST!=[]:
(b) DELETE FROM Shipping; print(POP(ST),end= “ ”)
else:
29. Write the definition of a function Reverse (x) in
break
Python, to display the elements in reverse order
or
such that each displayed element is the twice of
Alam has a list containing 10 integers. You need
the original element (element *2) of the List x in
to help him create a program with separate user
the following manner:
defined functions to perform the given operations
Example :
based on this list.
If List x contains 7 integers is as follows:
(a) Traverse the content of the list and push the
x [0] x [1] x [2] x [3] x [4] x [5] x [6] even numbers into a stack.
(b) Pop and display the content of the stack.
4 8 7 5 6 2 10 For example, If the sample content of the list is
After executing the function, the array content as follows
should be displayed as follows: N = [12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
20 4 12 10 14 16 8
38 22 98 56 34 12
Sol : Sol :
def Reverse (x): N = [12,13,34,56,21,79,98,22,35,38]
for i in range (len (x)–1,–1,–1): def PUSH(S, N):
Page 7 Sample Paper 1 Computer Science Class 12

S.append(N) Answer the following questions with respect to


def POP(S): the above :
if S!=[]: (i) Suggest a suitable cable layout for the network.
return S.pop() (ii) Suggest the best place to house the server of
else: the network.
return None (iii) Which topology should be used to connect
ST=[ ] computers in each building?
for k in N: (iv) What kind of network will be formed here?
if k%2==0: (LAN/MAN/WAN)
PUSH(ST,k) (v) Write one advantage of the topology suggested
while True: by you.
if ST!=[]:
print(POP(ST),end=“ ”) Sol :
else: (i) The cable layout is given below :
break

Section - D
31. Red Pandas Infosystems has its 4 blocks of
buildings. The number of computers and distances
between them is given below :

(ii) ADMIN building , as it has the maximum


number of computers.
(iii) Star topology, as it is the topology offering
best facilities,
(iv) LAN – Local Area Network
(v) Fault detection is easy.

32. (a) Find the output of the following Python


Building Number of Computers program:
HR 15 def makenew (mystr):
newstr = “”
ADMIN 100
count = 0
SYSTEM 25 for i in mystr:
PERS 30 if count%2!=0:
newstr = newstr + str (count)
else:
Building Distance if islower (i):
HR -Admin 10 m newstr = newstr + upper (i)
HR- System 50 m else:
newstr = newstr + i
HR- Pers 750 m count + = 1
Admin- System 300 m newstr = newstr + mystr [:1]
Admin- Pers 20 m
print(“The new string is:”,
newstr)
System-Pers 250 m makenew(“sTUdeNT”)
Page 8 Sample Paper 1 Computer Science Class 12

(b) Consider the table Student whose fields are from database Mobile.
Consider:
Scode Name Age Strcde Points Grade host : localhost
101 Amit 16 1 6 NULL UserName : root
102 Arjun 13 3 4 NULL Password : system
Database : Mobile
103 Zaheer 14 2 1 NULL
Sol :
104 Gegen 15 5 2 NULL
(a) strl=input(“Enter the string:”)
105 Kumar 13 6 8 NULL final= “ ”
Write the Python code to update grade to ‘A’ for for i in range (len(str1)):
all these students who are getting more than 8 as if (i%2==0):
points. final = final + strl[i]
print(“Modified string is :”, final)
The table structure is as follows :
(b) import mysql.connector as mydb
Scode : integer
mycon=mydb.connect (host =
Name : varchar
“localhost”,
Age : integer
user = “root”, passwd = “system”,
Strcde : integer
database = “Mobile”)
Points : integer
cursor = mycon.cursor ()
Grade : varchar
sql = “SELECT M_Id. M_Name,
Note the following to establish the connection
M_Supplier FROM MobileStock”
between Python and MySQL:
try:
Host : localhost
cursor.execute (sql)
Username : Admin
display = cursor, fetchall()
Password : Admin@123
for i in display
The table exists in MySQL database as : Student
print (i)
Sol : except:
(a) Output mycon.rollback()
The new string is : S1U3E5Ts mycon.close()
(b) import mysql.connector as mydb 33. What is CSV file?
con = mydb.connect (host = Write a program using two functions :
“localhost”, (a) addCustomer( ): To write Customer code,
user = “Admin”, Customer name and Amt in file “cust.csv”.
passwd = “Admin@123”, The details of the customers are as follows :
database = “system”) [‘CustCode’, ‘CustName’, ‘Amount’]
cursor = con.cursor ( ) [‘001’, ‘Nihir’, ‘8000’]
sql = “UPDATE Student SET Grade = [‘104’, ‘Akshay’, ‘5000’]
‘A’ WHERE Points > 8” (b) readCustomer( ): To read the details of the
try : customers and display them.
cursor. execute (sql)
con.commit ( ) Sol :
except : CSV (Comma Separated Values) is a file format
con.rollback ( ) for data storage which looks like a text file.
con.close ( ) Program:
or import csv
(a) Write a Python program to remove the def addCustomer():
characters of odd index values in a string. f1 = open(‘cust.csv’, ‘w’, newline
(b) Consider the table MobileStock with following = “\n”)
fields w1= csv.writer(f1, delimiter =
M_Id. M_Name, M_Oty, M_Supplier “;”)
Write the Python code to fetch all records w1.writerow([‘CustCode’,
with fields M_Id, M_Name and M_Supplier ‘CustName’, ‘Amount’])
Page 9 Sample Paper 1 Computer Science Class 12

w1.writerow(‘001’, ‘Nihir’, else:


‘8000’]) break
w1.writerow([‘104’, ‘Akshay’, def Display():
‘5000’]) f = open(“Inventory.csv”, “r”)
f1.close() dt = reader(f)
def readCustomer(): data = list(dt)
with open(“cust.csv”, ‘r’, “\n”) f.close()
as file1: for i in data:
reader = csv.reader(file1, for j in i:
delimiter = “;”) print(‘\t’, j, end= “ ”)
for row in reader: print()
print(row) getInventory()
file1.close() Display()
addCustomer()
readCustomer()
or Section - E
When do we use CSV file?
Write a program using following functions :
(a) getlnventory() : Write code to accept as many 34. Consider the table MOVIE DETAILS given below
inventory records and store them to the csv
Table : MOVIEDETAILS
file Inventory.csv storing records of inventory
as per following structure MOVIEID TITLE LANGUAGE RAT- PLAT-
ING FORM
PCode Invname Price Reorder
(b) Display() : To display the detail that store in M001 Minari Korean 5 Netflix
Inventory.csv M004 MGR Tamil 4 Hotstar
Magan
Sol :
M010 Kaagaz Hindi 3 Zee5
Data has a strict tabular structure.
M011 Harry English 4 Prime
To transfer large data between programs. Potter Video
To import and export data. and the
Program: Chamber of
Secrets
from csv import writer
def getInventory(): M015 Uri Hindi 5 Zee5

with open(“Inventory.csv ”, M020 Avengers: English 4 Hotstar


“a”,newline=“\n”) as f: Endgame

dt = writer(f) (i) Identify the degree and cardinality of the


while True: table.
pcode = int(input(“Enter (ii) Which field should be made the primary key?
Inventory code:”)) Justify your answer.
inv_name = input(“Enter (iii) Write statements to :
inventory name:”) (a) Delete the records whose language is
price = eval(input(“Enter “English”
Price:”)) (b) Add a new record : “M050”,
rol = int(input(“Enter reorder “Palki”,“Hindi”, 5, “Amazon Prime”.
level:”)) or (Option for part (iii) only)
dt.writerow([pcode, inv_name, Write statements to :
price, rol]) (a) Add a new column “DAYS” of type
print(“Record has been added.”) integer
print(“Want to add more record? (b) Remove the column “RATING”
Sol :
Type YES!!!”)
ch = input()
ch = ch.upper() (i) Degree is 5. Cardinality is 6.
if ch==“YES”: (ii) MOVIEID should be made the primary key
printr(“********************”) as it uniquely identifies each record of the
Page 10 Sample Paper 1 Computer Science Class 12

table.
(iii) (a) DELETE FROM MOVIEDETAILS WHERE
LANGUAGE=“ENGLISH”;
(b) INSERT INTO MOVIEDETAILS VALUES
(“M050”,“Palki”,“Hindi”, 5,
“Amazon Prime”);
or
(a) ALTER TABLE MOVIEDETAILS ADD
DAYS INTEGER;
(b) ALTER TABLE MOVIEDETAILS DROP
RATING;

35. Below is a program to delete the line having word


(passed as argument). Answer the questions that
follow to execute the program successfully.
import ......
def filedel (word):
file1 = open (“Python. txt ”,
“......”)
nfile = open (“algo1.txt”, “w”)
while True:
line = file1.readline( )
if not line:
break
else :
if word in line :
......
else :
print(line)
nfile......(line)
file1.close()
nfile.close()
filedel (‘write’)
(i) Name the module that should import in Line
1.
(ii) In which mode, above program should open
the file to delete the line?
(iii) Fill the blank in Line 11 and Line 14.
Sol :
(i) os
(ii) r
(iii) pass, write
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 2 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

Sol :
Section A (b) Foreign key

1. Given L= [2,3,4,5,6]. The output of print(L[–2]) is 6. Which method returns the next row from the
(a) 6 (b) Error result set as tuple?
(c) 5 (d) 3 (a) fetchone () (b) fetchmany ()
(c) fetchall () (d) rowcount
Sol :
Sol :
(c) 5
(a) fetchone ()
2. The method used to get the position of file pointer
is 7. Which of the following command displays the
(a) tell() (b) get() attributes of a table along with their types and
(c) seek() (d) pos() sizes?
(a) Alter
Sol :
(b) Show structure
(a) tell() (c) Show create table
(d) View structure
3. This function is used to calculate total occurrence
of given elements of list. Sol :
(a) len() (b) sum() (c) Show create table
(c) count() (d) extend()
8. The............command adds records to a table.
Sol :
(a) ADD (b) APPEND
(c) count() (c) ADDRECORD (d) INSERT
4. You can repeat the elements of the tuple using Sol :
which operator? (d) INSERT
(a) * (b) +
(c) ** (d) % 9. In a............topology, the nodes are connected by
separate cables.
Sol :
(a) Star (b) Bus
(a) * (c) Tree (d) Mesh

5. The rule of referential integrity is based on........... Sol :


(a) Primary key (b) Foreign key (a) Star
(c) Alternate key (d) None of these
Page 2 Sample Paper 1 Computer Science Class 12

10. Given a list Lst= [45,100,20,30,50]. What will be (c) uniquely identify a record
the output of Lst[: :]?
(a) [45,100,20,30,50] (b) [ ] Directions : (Q.Nos.-17 and 18) are Assertion and
(c) Error (d) [45] Reason based Questions.

Sol : 17. Assertion (A) To use the randint() function ,


(a) [45,100,20,30,50] the random module needs to be included in the
program.
11. State True or False Reason (R) Some functions are present in modules
“Given a dictionary Studict. The statement and to use them the respective module needs to
Studict.items() displays the keys of the item be imported.
only.” (a) Both A and R are true and R is the correct
explanation of A.
Sol :
(b) Both A and R are true but R is not the
False correct explanation of A.
(c) A is true but R is false.
12. Which module is to be imported to use the floor()
(d) A is false but R is true.
function?
(a) statistics (b) matplotlib Sol :
(c) random (d) math (a) Both A and R are true and R is the correct
Sol : explanation of A.
(d) math 18. Assertion (A) The contents of a Binary file are
not directly interpretable.
13. Which function is used to convert string into
Reason (R) Modes in which binary files can be
tuple?
opened are suffixed with ‘b’ like : rb/wb etc.
(a) string() (b) tup()
(a) Both A and R are true and R is the correct
(c) tuple() (d) str_tuple()
explanation of A.
Sol : (b) Both A and R are true but R is not the
(c) tuple() correct explanation of A.
(a) A is true but R is false.
14. A file can be opened both for reading and writing (c) A is false but R is true.
using............mode. Sol :
(a) r (b) r+
(c) a (d) None of these (c) A is true but R is false.

Sol :
(b) r+ Section - B
15. The..........clause can be used as an alternative to
19. Find the error(s).
multiple OR.
L1 = [7, 2, 3, 4] Statement 1
(a) IN (b) BETWEEN
L2 = L1 + 2 Statement 2
(c) NOT (d) range
L3 = L1 * 2 Statement 3
Sol : L = L1.pop(7) Statement 4
(a) IN Sol :
16. The purpose of the primary key in a database is Error 1 L2 = L1 + 2 because + operator cannot
to add list with other type as number or string.
(a) unlock the database Error 2 L = L1.pop(7) parentheses puts index
(b) provide a map of the data value instead of element. In the given list,
(c) uniquely identify a record maximum index value is 3 and 7 is out of index
(d) establish constraints on database operations range.

Sol : 20. Name two switching techniques used to transfer


data between two terminals (computers).
Page 3 Sample Paper 1 Computer Science Class 12

Sol : (b) Following are the three main types of computer


Switching techniques used to transfer data networks, based upon the geographical area
between two terminals are: as follows:
(i) Circuit switching (ii) Packet switching (i) Local Area Network (LAN)
or (ii) Metropolitan Area Network (MAN)
Arrange the following network in ascending order (iii) Wide Area Network (WAN)
of their area:
LAN, PAN, WAN, MAN 24. Identify the output of the following Python code.
D = {1: “One”, 2: “Two”, 3: “Three”}
Sol : L = [ ]
PAN < LAN < MAN < WAN for K, V in D.items():
if V[0] = = “T”:
L.append (K)
21. (a) Observe the code and write the output:
print(L)
t = ‘HELLO’
t1 = tuple(t) Sol :
print(t1) Output
(b) Predict the output of the following code [2, 3]
x = (1, 2, 3) or
y = (3, 4) Identify the output of the following Python
t = x + y statement.
print(t) lst1 = [10, 15, 20, 25, 30]
Sol : lst1.insert(3, 4)
lst1.insert(2, 3)
(a) (‘H’, ‘E’, ‘L’, ‘L’, ‘O’)
print (lst1[– 5])
(b) (1, 2, 3, 3, 4)
Sol :
22. Differentiate between an attribute and a tuple
3
with an example.
Sol : 25. Describe the following terms
(i) Domain
The columns of a table are referred to as attributes.
(ii) DB2
It is also known as field which is reserved for a
specific piece of data. The rows of a table are Sol :
referred to as tuples. (i) Domain is a set of possible values for an
e.g. attribute. A domain is said to be atomic,
if elements of the domain are considered as
indivisible units.
(ii) DB2 is a Relational Database Management
System (RDBMS), fully featured, high
performance database capable of handling
large quantities of data and concurrently
serving many users.
or
Identify commands/functions for the following
23. (a) Write the hill forms of
actions :
(i) WVVW
(i) To add a new column to a table.
(ii) TCP/IP
(ii) To get the sum of all values in a column of a
(b) List down the types of computer networks.
table.
Sol :
Sol :
(a) (i) World Wide Web
(i) ALTER TABLE <table_name> ADD
(ii) Transmission Control Protocol/Internet
column name datatype;
Protocol
(ii) SUM( )
Page 4 Sample Paper 1 Computer Science Class 12

Section - C 4
(ii) Make
5
26. (a) Consider the tables CARS and SUPPLIER (iii) CarName
given below. What will be the output of the SX4
statement given? C-Class
(iv) SUM(Charges)
TABLE: CARS
26
Ccode Car- Make Color Capa- Cha- Scode
Name city rges 27. Write a function Del() to delete the 4th word
501 A-star Suzuki RED 3 14 1 from a text file school.txt.
503 Indigo Tata SILVER 3 12 2 Sol :
502 Innova Toyota WHITE 7 15 2 def Del():
509 SX4 Suzuki SILVER 4 14 2 with open(‘school.txt’, ‘r’) as f:
510 C-Class Merc- RED 4 35 4 l = f.readlines()
edes f.close()
print(l)
Table : SUPPLIER del l[3]
print(l)
Scode Sname f = open (‘school.txt’, ‘w’)
1 Great Suppliers f.writelines(l)
2 Himalayan Vehicles f.close()
or
3 Road Motors Write a function countmy( ) in Python to read
4 Speed the text file “Data.txt” and count the number of
times “my” occurs in the file.
SELECT CarName, Sname, Charges FROM
For example If the file contents are:
CARS C, SUPPLIER S WHERE C.Scode= S.
My first book was. Me and My Family.
Scode AND Charges > 15;
It gave me chance to be known to the world.
(b) Write the output for SQL queries (i) to (iv),
The output of the function should be
which are based on the table CARDEN.
No. of times “my” occur : 2
TABLE: CARDEN
Sol :
Ccode CarName Make Color Capa- Charges
city def countmy():
501 A-star Suzuki RED 3 14
f=open(“Data.txt”, “r”)
count=0
503 Indigo Tata SILVER 3 12
x=f.read()
502 Innova Toyota WHITE 7 15 word=x.split()
509 SX4 Suzuki SILVER 4 14 for i in word:
510 C-Class Mercedes RED 4 35 if(i== “my”):
count=count+1
(i) SELECT COUNT(DISTINCT Make) FROM
print(“No. of times my occur :”,
CARDEN;
count)
(ii) SELECT COUNT(*) Make FROM CARDEN;
countmy()
(iii) SELECT CarName FROM CARDEN WHERE
Capacity = 4;
(iv) SELECT SUM (Charges) FROM CARDEN 28. (a) Write the output of the queries (i) to (iv)
WHERE Color = “SILVER”; based on the table FURNITURE given below.
Sol : Table : FURNITURE

(a) CarName Sname Charges FID NAME DATE OF COST DISCOUNT


PURCHASE
C-Class Speed 35
(b) (i) COUNT (DISTINCT Make)
Page 5 Sample Paper 1 Computer Science Class 12

del phone book [name]


B001 Double 03-JAN-2018 45000 10
Bed else:
print (“Name not found”)
T010 Dinning 10-MAR-2020 51000 5
Table print (“Phonebook Information”)
B004 Single 19-JUL-2021 22000 0
print (“Name”, \t, “Phone no”)
Bed for i in phonebook.keys ():
C003 Long 30-DEC-2016 12000 3
print (i, \t, phonebook [i])
back
Chair
30. Write Push (contents) and Pop (contents)
T006 Console 17-NOV-2019 15000 12 methods in Python to add numbers and remove
Table
numbers considering them to act as Push and Pop
B006 Bunk 01-JAN-2021 28000 14
operations of stack.
bed

(i) SELECT SUM(DISCOUNT) FROM Sol :


FURNITURE WHERE COST>15000; def Push(contents):
(ii) SELECT MAX(DATEOFPURCHASE) if(len(stack)>=limit):
FROM FURNITURE; print(“Stack Overflow!”)
(iii) SELECT * FROM FURNITURE WHERE else:
DISCOUNT>5 AND FID LIKE “T%”; stack.append(contents)
(iv) SELECT DATEOFPURCHASE FROM print(“Stack after Push”, stack)
FURNITURE WHERE NAME IN def Pop( ):
(“Dinning Table”, “Console if(len(stack)<=0):
Table”); print(“Stack Underflow!”)
(b) Write a command to remove all the records return 0
of the table “Garments” whose Readydate is else :
after “20-Oct-2008”. return stack Pop( )
Sol : or
Write the Push operation of stack containing
person names. Notice that the name should only
accept characters, spaces and period (.) except
digits. Assume that Pname is a class instance
attribute.
Sol :
def insert():
name_pattern = re.compile (r
“[A-Za-zs.]”)
while True
n = input (“Enter name:”)
while name_pattern. search (n):
print (“Invalid name”)
print (“Enter name correctly”)
(b) DELETE FROM Garments WHERE n = input( )
Readydate> “2008-10-20”; Sname.append (n)
c = input (“Enter more name
29. Write a user-defined function find-name (name), <y/n>”).upper( )
where name is an argument in Python to delete if (c! = ‘y’):
phone number from a dictionary phone-book on break
the basis of the name, where name is the key.
Sol :
def find-name (name):
if phone book.has_key ():
Page 6 Sample Paper 1 Computer Science Class 12

Section - D (ii) Building Z as it has the largest number of


computers.
(iii) (a) Switch/Hub to be placed in all the offices.
31. Sony corporation has set up its 4 offices in the (b) Repeater to be placed between Z-U.
city of Srinagar, with its offices X, Z, Y, U: (iv) Star topology
(v) Fault detection and isolation is easy.

32. (a) Carefully observe the following Python code


and answer the question that follow:
x = 5
def func2():
x = 3
global x
Branch to Branch distance is given below: x = x + 1
print(x)
X to Z 40 m
print(x)
Z to Y 60 m On execution the above code, produces the
Y to X 135 m following output:
6
X to U 70 m 3
Z to U 165 m Explain the output with respect to the scope of
Z to U 80 m the variables.
(b) Write the code to create a table Product in
Number of computers in each of the offices is as database Inventory with following fields
follows:
Fields Datatype
X 50
PID varchar(5)
Z 130
PName char(30)
Y 40
Price float
U 15
Rank varchar(2)
(i) Suggest a suitable cable layout of connectivity
of the offices. Note the following to establish the connection
(ii) Suggest placement of server in the network between Python and MySQL:
with suitable reason. Host : localhost
(iii) Suggest placement of following devices in the Username : system
network: Password : hello
(a) Switch/Hub Database : Inventory
(b) Repeater
(iv) Suggest a suitable topology for connecting Sol :
the computers in each building. (a) Names declared with global keyword have to
(v) Write any one advantage of the topology be referred at the file level. This is because the
suggested. global statement indicates that the particular
Sol : variable lives in the global scope. If no global
statement is being used, the variable with the
(i) local scope is accessed.
Hence, in the given code the statement
succeeding the statement global x informs
Python to increment the global variable x.
Hence, the output is 6 i.e. 5 + 1 which is also
the value for global x. When x is reassigned
with the value 3, the local x hides the global
x and hence 3 is printed.
Page 7 Sample Paper 1 Computer Science Class 12

(b) import mysql.connector 33. Does python create a file itself if the file doesn’t
mycon = mysql.connector.connect exist in the memory? Illustrate your answer with
(host = “localhost”, user = an example:
“system”, passwd = “hello”, Write a program using following functions :
database =“Inventory”) (a) inputStud() :To input details of as many
cur = mycon.cursor() students and add them to a csv file “college.
db = cur:execute (“CREATE TABLE csv” without removing the previous records.
Production (PID varchar SrNo Studname City Percentage
(5) Primary key,
PName char (30), (b) readCollege() : To open the file “college.csv”
Price float, and display records whose city is “Kolkata”
Rank varchar(2)))”
Sol :
mycon.close( )
or Python will create a file automatically when the
(a) Find the output of the following program: open function is used with write mode.
def calcresult (): Example:
i=9 f=open(“data.txt”, “w”)
while i>1 : f.write(“Hello\nHow are you?”)
if(i%2 = = 0): f.close()
x = i%2 Program:
i = i – 1 import csv
else: def inputStud() :
i = i – 2 with open(“.college.csv”,”a”) as f:
x = i dt = writer(f)
print(x**2) while True:
(b) Which data will get added in table Company sno= int(input(“Enter Serial
by following code? No:”))
import mysql.connector stud_name = input(“Enter student
con = mysql.connector.connect ( name:”)
host = “localhost”, city = input(“Enter city:”)
user = “system”, perc = int(input(“Enter
passwd = “hello”, percentage:”))
database = “connect”). dt.Writerow([sno, stud_name,
cur = con.cursor ( ) city, perc])
sql = “insert into Company (Name, print(“Record has been added.”)
Dept, Salary) values (%s, print(“Want to add more record?
%s, %s)” Type YES!!!”)
val = (“ABC”, “DBA”, 35000) ch = input()
cur.execute (sql.val) ch = ch.upper()
con.commit ( ) if ch==“YES”:
Consider : print(“*********************”)
host : localhost else:
UserName : system break
Password : hello def readCollege():
Database ; connect with open(“college.csv”, ‘r’,)
as file:
Sol :
reader = csv.reader(file)
(a) Output for row in reader:
49 if row[2]== “Kolkata”
25 print(row)
9 file.close()
1 inputStud()
(b) “ABC”, “DBA”, 35000 readCollege()
Page 8 Sample Paper 1 Computer Science Class 12

or Section - E
Write a statement to create a data.txt file with
the following text.
Python file handling is very interesting and useful. 34. Consider the table APPLICANTS
Write a python code using two functions as follows
TABLE: APPLICANTS
(a) removerow( ) : To remove a record from the
college file “College.csv” having following No NAME FEE GEN- C_ JOINYEAR
DER ID
structure.
1012 Amandeep 30000 M A01 2012
SrNo Studname City Percentage
1102 Avisha 25000 F A02 2009
(b) getCollege( ) : To read the records of the
1103 Ekant 30000 M A02 2011
college file “College.csv” and display names of
students whose names start with a lowercase 1049 Arun 30000 M A03 2009
vowel. 1025 Amber 40000 M A02 2011
1106 Ela 40000 F A05 2010
Sol :
1017 Nikita 35000 F A03 2012
f=open(“data.txt”, “w”)
1108 Arluna 30000 F A03 2012
f.write(“Python file handling is very
interesting and useful.”) 2109 Shakti 35000 M A04 2011
f.close() 1101 Kirat 25000 M A01 2012
Program : (i) Which field qualifies to be the Primary key.
import csv (ii) If all the records of Male applicants are
def removerow( ): deleted, what will be the cardinality of the
record = list() table.
sname= input(“Please enter a (iii) Write statements to
customer name to delete:”) (a) Increase FEE of “M” (Male) applicatnts
with open(‘College.csv’, ‘r’) by 2000.
as f: (b) Display details of “F” (Female) applicants
data = csv.reader(f) in descending order of FEE.
for row in data: or
record.append(row) (Option for part (iii) only)
for field in row: Write statements to
if field == sname: (a) Change width of column FEE to 20.
record.remove(row) (b) Remove the column C_ID.
with open(‘College.csv.’, ‘w’)
as f: Sol :
writer = csv.writer(f) (i) The No column can be the Primary key.
writer.writerows(record) (ii) 4
def getCollege(): (iii) (a) UPDATE APPLICANTS SET
with open(“College.csv”, ‘r’) FEE=FEE+2000 WHERE GENDER =
as file: “M”;
reader = csv.reader(file) (b) SELECT * FROM APPLICANTS WHERE
for row in reader: GENDER = “F” ORDER BY FEE DESC;
if row[1][0] in ‘aeiou’: or
print(row) (a) ALTER TABLE APPLICANTS MODIFY
file.close() FEE INTEGER (20);
removerow() (b) ALTER TABLE APPLICANTS DROP C_
getCollege() ID;

35. Given below is a code to open a text file and


perform some operations on it. Answer questions
with respect to the code given
myfile=open(“detail.txt”, “r”)
Page 9 Sample Paper 1 Computer Science Class 12

s =.......... Line 2
print(s)
myfile.close( )
(i) In which mode is the file opend?
(ii) If the entire file is to be read, write a statement
in place of Line 2.
(iii) What is the original code performing?
Sol :
(i) Read mode
(ii) s=myfile.read( )
(iii) The code opens a text file “detail.txt”, reads
10 characters from it and displays them.
Finally, the file is closed.
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 3 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

Sol :
Section A (a) Relative

1. What is default value of host? 6. _____command adds a primary key to a table


(a) host (b) localhost after it has been already created.
(c) globalhost (d) None of these (a) MODIFY (b) ADD PRIMARY
(c) ALTER (d) ADD KEY
Sol :
Sol :
(b) localhost
(c) ALTER
2. Which of the following SQL commands displays
the structure of a table? 7. The clause to get the unique values from a field
(a) ALTER (b) STRUCTURE of a table is
(c) DESCRIBE (d) SHOW DATA (a) MAX (b) UNIQUE
(c) DISTINCT (d) None of these
Sol :
Sol :
(c) DESCRIBE
(c) DISTINCT
3. State True or False
“Lists and dictionaries are mutable.” 8. Observe the following tuples and choose the
correct option
Sol :
t1=(4, 7, 8, 9)
True t2=(0, 4, 3)
>>>t=t1+t2
4. Which of the following is the correct output for
>>>print(t)
the execution of the following Python statement?
(a) (4, 7, 8, 9, 0, 4, 3) (b) (4, 7, 8, 9, 4, 7, 8, 9)
(b) (4, 7, 8, 9) (d) None of these
print(5+3**2/2)
(a) 32 (b) 8.0
(c) 9.5 (d) 32.0 Sol :

Sol : (a) (4, 7, 8, 9, 0, 4, 3)

(c) 9.5 9. ______is an attribute that makes a link


between two tables to fetch corresponding data.
5. Which path does not start with a leading forward
(a) Primary key (b) Secondary key
slash ? (c) Foreign key (d) Composite key
(a) Relative (b) Absolute
(c) Both (a) and (b) (d) None of these Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(c) Foreign key 15. Which of the following function returns the total
number of values?
10. Assume that the position of the file pointer is at (a) MAX (b) MIN
the beginning of 3rd line in a text file. Which of (c) COUNT (d) SUM
the following option can be used to read all the
remaining lines? Sol :
(a) myfile.read(n-3) (b) myfile.read(n) (c) COUNT
(c) myfile.readline( ) (d) myfile.readlines( )
16. Which of the following is the correct output for
Sol : the following execution ?
(d) myfile.readlines( ) print(print(“Biscope”))
(a) Biscope (b) None
11. ______is a protocol used for uploading and (c) Biscope (d) Error
downloading of files in a network. None
(a) SMTP (b) FTP
(c) PPP (d) VoIP Sol :

Sol : (c) Biscope


None
(b) FTP
Directions : (Q. Nos. 17 and 18) are Assertion
12. sub = “PYTHON” and Reason based questions.
for i in sub:
print (i, ‘ ’, end = “ ”) 17. Assertion (A) A Python function that accepts
parameters can be called without any parameters.
Reason (R) Functions can carry default values
that are used, whenever values are not received
(a) PYTHON (b) from calling function.
(a) Both A and R are true and R is the correct
explanation of A.
(b) Both A and R are true but R is not the
(c) None (d) P, Y, T, H, O, N correct explanation of A.
Sol : (c) A is true but R is false.
(d) A is false but R is true.
(a) PYTHON
Sol :
13. In complex number a + ib, b represents as
(a) Both A and R are true and R is the correct
(a) real part
explanation of A.
(b) imaginary part
(c) special part 18. Assertion (A) A CSV file is by default delimited
(d) None of these by comma(,), but the delimiter character can be
Sol : changed.
Reason (R) The writerow() function for CSV files
(b) Imaginary part
has a “delimiter” parameter that can be used to
14. Given an object obj1= (10, 20, 30, 40, 50, specify the delimiter to be used for a CSV file.
60, 70, 80, 90). What will be the output of (a) Both A and R are true and R is the correct
print(obj1[3:7:2])? explanation of A.
(a) (40,50,60,70,80) (b) Both A and R are true but R is not the
correct explanation of A.
(b) (40,50,60,70)
(c) A is true but R is false.
(c) (40,50,60) (d) A is false but R is true.
(d) (40,60) Sol :

Sol : (a) Both A and R are true and R is the correct


explanation of A.
(d) (40,60)
Page 3 Sample Paper 1 Computer Science Class 12

Section - B 23. (a) Write the full forms of the following


(i) WAN (ii) GSM
(b) Write down the expansion of Modem. Also,
19. What will be the output for the following Python
write its role in a network.
statement?
L = [10, 20, 30, 40, 50] Sol :
L = L + 5 (a) (i) Wide Area Network.
print(L) (ii) Global System for Mobile communication.
Sol : (b) A Modem stands for ModulatorDemodulator.
It is a network device used for conversion of
Error, the list data type does not allow addition of
signals from digital to analog and analog to
integers with it. So, L + 5 is an invalid statement.
digital.
20. Write any two disadvantages of star topology.
24. Write the output of given code :
Sol : x = (1, 2, 3)
(a) Costly due to individual cables for each node. y = (3, 4)
(b) Central node dependency. t = x + y
or print(t)
Why is a switch called an intelligent hub? Sol :
Sol : (1, 2, 3, 3, 4)
A switch is also known as intelligent hub because or
a hub forwards each incoming packet (data) to all Observe the following tuple and answer the
the hub ports. Whereas, a switch forwards each questions that follow:
incoming packet to the specified recipient. t1 = (70, 56, ‘Hello’, 22, 2, ‘Hi’,
‘The’, ‘World’, 3)
21. (a) What will be the output of the following (i) t1[2 : 4] (ii) t1[– 6]
Python code?
Sol :
L =[10, 20]
L1=[30, 40] (i) (‘Hello’, 22) (ii) 22
L2=[50, 60]
25. If R1 is a relation with 8 rows and 5 columns, then
L. append (L1)
what will be the cardinality of R1?
L.extend(L2)
If 5 rows are added more, what will be the Degree
print(L)
of the table now ?
(b) Find the output
>>> l1 = [1,2,3,4] Sol :
>>> l2 = [1,2,3,4] Cardinality means the number of rows in a table.
>>> l1 > l2 Degree means the number of columns of a table.
Sol : Relation R1 has 8 rows , so cardinality will be 8.
If 5 rows are added cardinality become 8+5 =13.
(a) [10, 20, [30, 40], 50, 60]
Degree remains the same, that is 5.
(b) False
or
22. Mention the various advantages of using a DBMS. Identify commands/functions for the following
actions
Sol :
(i) To display only records of Trains from the
DBMS has the following advantages: Train table whose starting station is “NDLS”.
(i) Reduced data redundancy (Column for starting station is “Start”, table
(ii) Elimination of inconsistency name is “Train”)
(iii) Data sharing (ii) To get the average of percentage of students
(iv) Data integrity (Table name : “Student” , Percentage column
(v) Data security : “Perc”).
(vi) Ease of application development
Sol :
Page 4 Sample Paper 1 Computer Science Class 12

(i) SELECT * FROM Train WHERE Start= (ii) SELECT CNAME FROM CUSTOMER
“NDLS”; WHERE CNAME LIKE ‘L%’;
(ii) SELECT AVG(Perc) FROM Student; (iii) SELECT DISTINCT AREA FROM
CUSTOMER;
(iv) SE.LECT’COUNT(*) FROM CUSTOMER
Section - C WHERE GENDER=“MALE”;
Sol :
26. (a) Consider the tables CITY and LOCATION
(a) SELECT C. Cityname , L.Lname FROM
given below.
City C,
Table : CITY LOCATION L WHERE C.Citycode= L.
Citycode AND AVGTEMP>35;
Field Name Data Type Remarks
(b) (i)
CITYCODE CHAR(5) Primary Key
COUNT (*) GENDER
CITYNAME CHAR(30)
4 FEMALE
SIZE INTEGER
AVGTEMP INTEGER
6 MALE
(ii) No rows selected
POPULATIONRATE INTEGER
(iii)
POPULATION INTEGER
DISTINCT AREA

Table: Location NORTH

Citycode Lname SOUTH

C1 East EAST

C2 West WEST
(iv)
C3 South
COUNT (*)
C4 North
6
Write a command to display the Cityname and
corresponding Location name (Lname), where the 27. Write a Python program that read the data from
average temperature is greater than 35 from the file ‘original.dat’ and delete the line(s) having
tables. word (passed as an argument). Then write these
(b) Write outputs for the SQL commands (i) to data after removing lines into file ‘duplicate.dat’.
(iv) based on the table CUSTOMER given
Sol :
below:
TABLE: CUSTOMER import os
def Delete (word):
CID CNAME GENDER SID AREA
file1=open(‘original.dat’, ‘rb’)
1001 R SHARMA FEMALE 101 NORTH nfile=open(‘duplicate.dat’, ‘wb’)
1002 M R TIWARY MALE 102 SOUTH while True :
1003 M K KHAN MALE 103 EAST line=file1.readline()
1004 A K SINGH MALE 102 EAST
if not line :
break
1005 S SEN FEMALE 101 WEST
else :
1006 R DUBEY MALE 104 NORTH if word in line :
1007 M AGARWAL FEMALE 104 NORTH pass
1008 S DAS FEMALE 103 SOUTH else:
print(line)
1009 R K PATIL MALE 102 NORTH
nfile.write(line)
1010 N KRISHNA MALE 102 SOUTH
file1.close()
MURTY
nfile.close()
(i) SELECT COUNT(*), GENDER FROM
or
CUSTOMER GROUP BY GENDER;
Page 5 Sample Paper 1 Computer Science Class 12

Write a program in Python to open a text file of each Name of ACCESSORIES.


“lines.txt” and display all those words whose (iv) To display Name, Price of all
length is greater than 5. ACCESSORIES and their respective
SName, where they are available.
Sol :
(b) Write a command to add a new column
f=open(“lines.txt”) Remarks varchar(30) to the ACCESSORIES
data=f.read() table storing remarks about the product.
str=data.split(‘ ’)
print(“Words with length greater Sol :
than 5”) (a) (i) SELECT Name, Price FROM
for w in str: ACCESSORIES ORDER BY Price;
if len(w)>5 : (ii) SELECT Id, SName FROM SHOPPE
print(w) WHERE Area = ‘Nehru Place’;
f.close() (iii) SELECT MIN(Price) “Minimum
Price”, MAX(Price) “Maximum
28. (a) Answer the questions (i) to (iv) on the Price”, Name FROM ACCESSORIES
basis of the following tables SHOPPE and GROUP BY Name;
ACCESSORIES. (iv) SELECT Name, Price, SName FROM
TABLE: SHOPPE ACCESSORIES A, SHOPPE S WHERE
A.Id = S.Id;
Id SName Area But this query enable to show the result
S001 ABC Computeronics CP because A.Id and S.Id are not identical.
(b) ALTER TABLE ACCESSORIES ADD COLUMN
S002 All Infotech Media GK II
Remarks varchar(30);
S003 Tech Shoppe CP
29. Write a userdefined function parser(L) that
S004 Geeks Tecno Soft Nehru Place
accepts a list as parameter and creates another
S005 Hitech Tech Store Nehru Place two lists storing the numbers from the original list
, that are even and numbers that are odd.
TABLE: ACCESSORIES Sol :
No Name Price Id newLeven=[ ]
A01 Mother 12000 S01 newLodd=[ ]
Board i=j=0
def parser(L):
A02 Hard Disk 5000 S01
for num in L :
A03 Keyboard 500 S02 if num%2 ==0:
A04 Mouse 300 S01 newLeven[i]=num
i+=1
A05 Mother 13000 S02
else :
Board
newLodd[j]=num
A06 Keyboard 400 S03 j+=1
A07 LCD 6000 S04 print(“Even number list:”,
newLeven)
T08 LCD 5500 S05
print(“Odd number list:”,
T09 Mouse 350 S05 newLodd)
T10 Hard Disk 4500 S03
30. Consider the following stack of characters, where
(i) To display Name and Price of all the STACK is allocated N = 8 memory cells.
ACCESSORIES in ascending order of STACK : A, C, D, F, K,...,...,...
their Price. Describe the STACK at the end of the following
(ii) To display Id and SName of all SHOPPE operations. Here, Pop and Push are algorithms
located in Nehru Place. for deleting and adding an element to the stack.
(iii) To display Minimum and Maximum Price (i) Pop (STACK, ITEM)
Page 6 Sample Paper 1 Computer Science Class 12

(ii) Pop (STACK, ITEM) Section D


(iii) Push (STACK, L)
(iv) Push (STACK, P)
31. Trine Tech Corporation (TTC) is a professional
(v) Pop (STACK, ITEM)
consultancy company. The company is planning
(vi) Push (STACK, R)
to set up their new offices in India with its hub
(vii) Push (STACK, S)
at Hyderabad. As a network adviser, you have to
(viii) Pop (STACK, ITEM)
understand their requirement and suggest them
Sol : the best available solutions. Their queries are
The stack contents will be as follows after the mentioned as (i) to (v) below.
operations of stack :
(i) STACK : A, C, D, F
(K is deleted)
(ii) STACK : A, C, D
(F is deleted)
(iii) STACK : A, C, D, L
(L is inserted)
(iv) STACK: A, C, D, L, P
(P is inserted)
(v) STACK : A, C, D, L
(P is deleted) Block (From) Block (To) Distance

(vi) STACK : A, C, D, L, R Human Conference 110


Resource
(R is inserted)
Human Finance 40
(vii) STACK : A, C, D, L, R, S Resource
(S is inserted) Conference Finance 80
(viii) STACK : A, C, D, L, R Expected number of computers to be in each
(S is deleted) block
or Block Computers
Consider the following sequence of numbers:
Human Resource 25
1, 2, 3, 4
These are supposed to be operated through a stack Finance 120
to produce the following sequence of numbers: Conference 90
2, 1, 4, 3
List the Push and Pop operations to get the (i) Which will be the most appropriate block,
required output. where TTC should plan to install their server?
(ii) Draw a block to block cable layout to connect
Sol :
all the buildings in the most appropriate
(i) Push (1) manner for efficient communication.
(ii) Push (2) (iii) Suggest a suitable topology to connect the
(iii) Pop (2) computers in each building.
(iv) Pop (1) (iv) Which of the following device will be suggested
by you to connect each computer in each of
(v) Push (3)
the buildings?
(vi) Push (4)
(a) Switch/Hub (b) Modem (c) Gateway
(vii) Pop (4)
(v) Company is planning to connect its offices in
(viii) Pop (3) Hyderabad which is less than 1 km. Which
Page 7 Sample Paper 1 Computer Science Class 12

type of network will be formed? Note the following to establish the connection
between Python and MySQL:
Sol : Host : localhost
(i) TTC should install its server in finance Username : system
block as it is having maximum number of Password : test
computers. Database : Inventory
(ii) Sol :
(a) 50#5
(b) Yes, she can add new column after creation of
table.
import mysql.connector
mycon = mysql.connector.connect(
host = “local host”,
user = “system”,
passwd = “test”,
The above layout is based on minimum cable database = “Inventory”)
length required, which is 120 m in the above case. cursor = mycon.cursor( )
(iii) Star topology, as it has independent cursor.execute(“ALTER TABLE Item
connections that help easy network setup and ADD ManufacturingDate Date NOT
fault detection. NULL”) mycon.close ( )
(iv) (a) Switch/Hub These are devices that can or
connect multiple nodes in a network, (a) Find the output of the following code :
together. Name= “PythoN3@1”
(v) Since, the distance is less than 1 km. R=“ ”
LAN (Local Area Network) will be formed. for x in range(len(Name)):
if Name[x].isupper():
32. (a) What will be the output of the following R=R+Name[x].lower()
code? elif Name[x].islower():
value = 50 R=R+Name[x].upper()
def display(N): elif Name[x].isdigit():
global value R=R+Name[x–1]
value = 25 else:
if N%7==0 R=R+ “#”
value = value + N print(R)
else: (b) Consider the following table structure
value = value — N Table: Faculty
print(value. end= “#”) F_ID(P)
display(20) Fname
print(value) Lname
(b) Given below is a table Item in database Hire_date
Inventory. Salary
ItemID ItemName Quantity UnitPrice Write the Python code to create the above table.
Consider :
101 ABC 5 120
host : localhost
102 XYZ 7 70 UserName : root
103 PQR 8 65 Password : system
Database :School
104 XYZ 12 55
Riya created this table but forget to add column Sol :
ManufacturingDate. Can she add this column (a) pYTHOnN#@
after creation of table? If yes, write the code (b) import mysql.connector
where user’s name and password are system and mycon = mysql. connector.connect(
test respectively. host = “localhost”,
Page 8 Sample Paper 1 Computer Science Class 12

user = “root”, d = csv.reader(f)


passwd = “system”, next(f) #to skip header row
database = “School”) r = 0
cursor= mycon.cursor( ) for row in d:
db = cursor.execute (“CREATE TABLE r = r+l
Faculty(F_ID varchar(3) print(“Number of records are ” r)
Primary key, Fname varchar(30) f.close()
NOT NULL, addBook(),
Lname varchar(40), countRecords()
Hire_date Date, or
Salary Float)) Explain open( ) function with its syntax.
mycon.close( ) Write python code to perform the following using
two user defined functions.
33. What do you mean by file? What do you mean by (a) showData() : To display only roll no and
file handling? student name of the file “student.csv”
Write a program code in python to perform the
following using two functions as follows : RollNo, Name, Marks
(a) addBook( ) : to write to a csv file “book.csv” 1, Nilesh, 65
file book no, book name and no of pages with 2, Akshay, 75
separator as tab. (b) showSelect( ) : To display only roll number
(b) countRecords( ) : To count and display the and marks of the students from the csv file
total number of records in the “book.csv” file “student.csv”
Sol : Sol :
(i) The file refers to the collection of bytes stored (i) The open function has the following syntax:
in computer storage. (ii) Syntax:<file object> = open( file_
(ii) File handling refers to the process of handling name,access_mode)
data using software for I/O operations.
Program: (iii) file object : It is just like a variable or an
import csv object
def addBook(): (iv) open( ): It is a function with two parameters.
f1 = open(“book.csv”, ‘w’, newline
(v) file_name: It accepts a file name with .txt
= “\n”)
extension.
w1 = csv.writer(f1, delimiter
= “\t”) (vi) access_mode: It specifies the mode to access
w1.writerow([‘BookNo’,‘BookName’, the file. The default mode is reading mode.
‘Pages’]) Program:
while True: import csv
op = int(input(“Enter 1 to add def showData():
and 0 to exit”)) f = open(“student.csv”, ‘r’)
if(op == 1): r = csv.reader(f, delimiter = ‘,’)
Bookno = int(input(“Enter Book for row in r :
No: ”)) print(row[0], row[1])
Bookname = input(“Enter Book f.close()
Name: ”) def showSelect():
Pages = int(input(“Enter Pages: f = open(“student.csv”, ‘r’)
”)) r = csv.reader(f, delimiter = ‘,’)
w1.writerow([Bookno, Bookname, for row in r :
Pages]) print(row[0], row[2])
elif op == 0: f.close()
break showData()
f1.close() showSelect()
def countRecords():
f = open(“book.csv”,“r”)
Page 9 Sample Paper 1 Computer Science Class 12

lines=myf....... . Blank 3
Section-E for ln in .... . . : Blank 4
if ln[0]= = “A”:
34. Consider the following table STORE and answer print(ln)
the questions: (i) Write the missing code for Blank 1.
TABLE: STORE (ii) Write the missing code for Blank 2.
ItemNo Item Scode Qty Rate LastBuy
(iii) Write the missing code for Blank 3 and Blank
4.
2005 Sharpener 23 60 8 31-JUN-09
Classic Sol :
2003 Balls 22 50 25 01-FEB-10 (i) “para.txt”
2002 Gel Pen 21 150 12 24-FEB-10 (ii) “r”
Premium (iii) readlines( ), lines.
2006 Gel Pen 21 250 20 11-MAR-09
Classic
2001 Eraser 22 220 6 19-JAN-09
Small
2004 Eraser Big 22 110 8 02-DEC-09
2009 Ball Pen 0.5 21 180 18 03-NOV-09

(i) What is the degree of the table?


(ii) Write the syntax of the SQL command to
change data of the table.
(iii) Write statements to :
(a) Display the number of distinct Scodes.
(b) Display the maximum and minimum
quantities.
(Option for part (iii) only)
Write statements to :
(a) Display the structure of the STORE
table.
(b) Add a new column Location varchar(50)
in the table to store the location details
of the items.
Sol :
(i) Degree means the number of columns in a
table. The degree of the table is 6.
(ii) Update <Table> Set <Column> =
<Value/Expression> where <Conditi
on>;
(iii) (a) SELECT COUNT(DISTINCT Scode)
FROM STORE;
(b) SELECT MAX(Qty) , MIN(Qty) FROM
STORE;
or
(a) DESCRIBE STORE;
(b) ALTER TABLE STORE ADD Location
varchar(50);

35. Given below is a code to open a text file “para.


txt” and display the lines that begin with “A”.
Some of the codes are missing . Write codes to fill
up the blanks :
myf=open(... ,...) Blank 1 , Blank 2
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 4 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. The seek(n) places the file pointer at position n


Section A with reference to
(a) Beginning (b) End
1. Given L= [2,3,4,5,6]. The output of print(L[–1:–5]) (c) Current position (d) Position 10
is
Sol :
(a) [6,5,4] (b) Error
(c) [ ] (d) [6,5] (a) Beginning
Sol : 6. Given a tuple t= (2,5,1,6,3). The statement
(c) [ ] t.sort() returns
(a) (1,2,3,5,6) (b) (6,5,3,2,1)
2. Rows of a relation are called (c) Error (d) None of these
(a) relation
Sol :
(b) tuples
(c) data structure (c) Error
(d) an entity
7. t1=(9,6,7,6)
Sol : t2=(2.8,12,20)
(b) tuples The output of the statement below is
print( min(t1) + max(t2))
3. If a table carries 10 columns and 15 rows, what (a) 26 (b) 25
is its degree? (c) Error (d) None of these
(a) 10 (b) 150
Sol :
(c) 15 (d) 25
(a) 26
Sol :
(a) 10 8. State True or False
“The method that can be used to delete a range
4. The...........function returns True if all the of values from a list is del”.
characters in a string are digits.
Sol :
(a) isalnum()
(b) isdigit() True
(c) isnumber()
(d) isalpha() 9. In which module, ceil() function resides ?
(a) pandas (b) pyplot
Sol : (c) random (d) math
(b) isdigit() Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(d) math 17. Assertion (A) A function with 3 formal parameters


must be called with 3 actual parameters.
10. To see a list of all the databases in the system , Reason (R) Since, all the formal parameters are
the..............command may be used. used to produce the output from the function , the
(a) Show (b) Show databases function expects the same number of parameters
(c) Display databases (d) View databases from the function call.
Sol : (a) Both A and R are true and R is the correct
explanation of A.
(b) Show databases
(b) Both A and R are true but R is not the
11. Which among the following are constraints ? correct explanation of A.
(a) Primary key (b) Unique (c) A is true but R is false.
(c) NOT NULL (d) All of these (d) A is false but R is true.

Sol : Sol :
(d) All of these (a) Both A and R are true and R is the correct
explanation of A.
12. in and not in are........Operators.
(a) Arithmetic (b) Membership 18. Assertion (A) A binary file uses the dump()
(c) Logical (d) Identity function to write data into it.
Reason (R) The load() function reads data from
Sol : a binary file.
(b) Membership (a) Both A and R are true and R is the correct
explanation of A.
13. Modulation and demodulation is performed by (b) Both A and R are true but R is not the
(a) microwave (b) satellite correct explanation of A.
(c) modem (d) gateway (c) A is True but R is false.
Sol : (d) A is false but R is true.
(c) modem Sol :
(b) Both A and R are true but R is not the correct
14. A set of possible data values is called
explanation of A.
(a) attribute (b) degree
(c) tuple (d) domain
Sol : Section B
(d) domain
19. What will be the output of following code ?
15. The..........attribute of the connection string L=[10,30,50,60]
specifies the password to connect to the database. L.append(70)
(a) code (b) password L.insert(2,80)
(c) passwd (d) All of these L.sort()
Sol : print(L)
(c) passwd Sol :

16. While opening a binary file the.........character has [10, 30, 50, 60, 70, 80]
to be added to the mode of opening. 20. Write 2 advantage and 2 disadvantage of bus
(a) b (b) x topology.
(c) u (d) b*
Sol :
Sol :
Advantages of Bus Topology
(a) b (i) All the nodes are connected directly, so very
Directions (Q.Nos. 17-18) are Assertion and short cable length is required.
Reason based questions. (ii) The architecture is very simple, reliable and
linear.
Page 3 Sample Paper 1 Computer Science Class 12

Disadvantages of Bus Topology A primary key is a set of one or more attributes


(i) In case of any fault occurred In data that can uniquely identify tuples within the
transmission, fault isolation is very difficult. relation.
We have to check the entire network to find e.g.
the fault. TABLE: ITEM
(ii) Becomes slow with increase in number of
nodes. ItemNo Name State City
or 11 Pastry 10 Ajmer
Which part of TCP/IP is responsible for dividing
12 Pizza 15 Delhi
a file or message into very small parts, at the
source computer? Also, define, TCP/IP. 13 Cake 5 Pune
Sol : 14 Burger 35 Delhi
The attribute ItemNo is a primary key in ITEM
TCP/IP is the communication protocol for the
table as it contains unique value for each tuple in
Internet. It defines the rules, computers must
a relation.
follow to communicate with each other over the
Internet. The TCP/IP is a protocol used in E-mail 23. (a) Write the full forms of
transmission. (i) LAN (ii) XML
The TCP/IP is a protocol, which is responsible (b) What was the role of ARPANET in the
for finding path for the destination. It also, splits computer network?
the message into several datagrams, if it does not
Sol :
fit in one datagram. Therefore, these datagrams
are sent through different alternate paths towards (a) (i) Local Area Network.
the destination. The TCP makes sure that the (ii) Extensible Markup Language
datagram arrives at the destination correctly. (b) ARPANET (Advanced Research Projects
While IP is responsible for moving packet of data Agency Network) goal was to connect
from source to destination. It handles the address computers at different universities and US
part of each packet so that it reaches to the right defense. ARPANET started with a handful of
destination. computers but it expanded rapidly.

21. Find outputs of following code. 24. What will be the output of the following code,
(a) L=[118,16,[20,30,50],120] when executed?
L1=[12,16,17] d={‘Name’: ‘Ram’,‘Subjects’:[‘Eng’,
L.extend(L1) ‘Physics’, ‘CS’], ‘Marks’:[67,78,90]}
print(L[2][2]) print(d[‘Subjects’])
print(L) print(d[‘Subjects’][2])
(b) t1=(9,6,1,12) Sol :
t2=(10,11,12)
print(t1+t2) [‘Eng’,‘Physics’,‘CS’]
print(t1*2) ‘CS’
print(t2–t1) or
What will be the output of the following code,
Sol : when executed?
(a) 50 tupnames=(“India”, “Australia”,
[118, 16, [20, 30, 50], 120, 12, 16, 17] (“UK”, “Nepal”), “Bangladesh”)
(b) (9, 6, 1, 12, 10, 11, 12) print(tupnames[5 : ])
(9, 6, 1, 12, 9, 6, 1, 12) print(tupnames[2][1])
Error Sol :
22. What do you understand by primary key? Give ()
a suitable example of primary key from a table ‘Nepal’
containing some meaningful data.
25. List the major components of a database system.
Sol :
Sol :
Page 4 Sample Paper 1 Computer Science Class 12

The major components of a database system are 2002 Gel Pen 21 150 12 24-FEB-10
(i) User (ii) Hardware Premium
(iii) Software (iv) Data 2006 Gel Pen 21 250 20 11-MAR-09
or Classic
What is join? What are the different kinds of 2001 Eraser 22 220 6 19-JAN-09
joins? Small

Sol : 2004 Eraser Big 22 110 8 02-DEC-09


2009 Ball Pen 21 180 18 03-NOV-09
A join is a relational operation on a set of 0.5
relations to get corresponding data from the table
by linking them on a common field called the Write SQL commands for the following statements:
foreign key. (i) To display details of all the items in the
There are different kind of join STORE table in ascending order of LastBuy.
(a) Equi Join (b) Natural Join (ii) To display ItemNo and Item name of those
(c) Cross Join (d) Non Equi Join items from STORE table, whose Rate is more
than `15.
(iii) To display the details of those items whose
Supplier code (Scode) is 22 or Quantity in
Section C Store (Qty) is more than 110 from the table
STORE.
26. (a) Consider the tables Student and House (iv) To display minimum rate of items for each
given below. What will be the output of the Supplier individually as per Scode from the
statement given? table STORE.
Sol :
Table: Student
(a)
Rno Sname Class Hcode
Sname LName
1 Raj 12ScA C1
Raj East
2 Shekhar 11ComC C2
Ravi West
3 Ravi 12HumB C2 (b) (i) SELECT * FROM STORE ORDER BY
4 Jaisnav 12ScB C3 LastBuy;
(ii) SELECT ItemNo, Item FROM STORE
Table: House WHERE Rate>15;
(iii) SELECT * FROM STORE WHERE Scode
Hcode Lname = 22 OR Oty>110;
C1 East (iv) SELECT MIN(Rate) FROM STORE
C2 West GROUP BY Scode;

C3 South 27. Write a program to accept a filename and


C4 North a position. Using the inputs, call a function
SearchFile(Fname, pos) to read the contents of
SELECT S.Sname , H.Lname FROM Student the file from the position to the end. Now, display
S, House H WHERE S.Hcode = H.Hcode all those words that start with “U” or “u”.
AND SName LIKE “R%”;
(b) Consider the following table STORE and Sol :
answer the questions def SearchFile(Fname, pos):
TABLE: STORE
f=open(Fname, “r”)
f.seek(pos)
ItemNo Item Scode Qty Rate LastBuy
data=f.read()
2005 Sharpener 23 60 8 31-JUN-09 datawords=data.split(‘ ’)
Classic
for w in datawords :
2003 Balls 22 50 25 01-FEB-10 if w[o] in “uU” :
print(w)
Page 5 Sample Paper 1 Computer Science Class 12

or 10019 EVENING 850 F03 06-JUN-08


Write a program to search a Employee record GOWN
according to Id from the “emp.txt” file. The 10009 INFORMAL 1500 F02 20-OCT-
“emp.txt” file contains Id, Name and Salary PANT 08
fields. Assume that first field of the employee 10007 FORMAL 1350 F01 09-MAR-
records (between Id and Name) is separated with PANT 08
a comma(,). 10020 FROCK 850 F04 09-SEP-07

Sol : 10089 SLACKS 750 F03 20-OCT-


08
import os
f1=“emp.txt”
if os.path.isfile(f1): TABLE: FABRIC
fob=open(f1) FCODE TYPE
eid=int(input(“Enter employee F04 POLYSTER
id:”))
flag=False F02 COTTON
for emp in fob: F03 SILK
strlen=len(emp)
F01 TERELENE
i=0
strid=“ ” (i) To display GCODE and DESCRIPTION
while True of each GARMENT in descending order
if(emp[i]== “,”): of GCODE.
break (ii) To display the details of all the
if(emp[i]>=‘0’ and GARMENTs, which have READYDATE
emp[i]<=‘9’): in between 08-DEC-07 and 16-JUN-08
strid=strid+emp[i] (inclusive of both the dates).
i=i+1 (iii) To display the average PRICE of all the
nid=int(strid) GARMENTs. Which are made up of
if(eid==nid): FABRIC with FCODE as F03.
print(“Employee found: ”,emp) (iv) To display FABRIC wise highest and
flag=True lowest price of GARMENTs from
break GARMENT table. (Display FCODE of
fob.close( ) each GARMENT along with highest and
if(flag==False): lowest price.)
print(“Record does not found”)
(b) Write a command to remove the records of
else:
the garments whose READYDATE is after
print(“File does not exist”)
DEC-2008.
28. (a) Consider the following tables GARMENT Sol :
and FABRIC. Write SQL commands for the
(a) (i) SELECT GCODE, DESCRIPTION FROM
statements (i) to (iv).
GARMENT ORDER BY GCODE DESC;
TABLE: GARMENT (ii) SELECT*FROM GARMENT WHERE
GCODE DESCRIPTION PRICE FCODE READY- READYDATE BETWEEN ‘08-DEC-07’
DATE AND ‘16-JUN-08’:
10023 PENCIL SKIRT 1150 F03 19-DEC-08 (iii) SELECT AVG(PRICE) FROM GARMENT
WHERE FCODE = ‘F03’:
10001 FORMAL 1250 F01 12-JAN-08
SHIRT (iv) SELECT FCODE, MAX(PRICE),
MIN(PRICE) FROM GARMENT GROUP
10012 INFORMAL 1550 F02 06-JUN-08
SHIRT BY FCODE;
(b) DELETE FROM GARMENT WHERE READYDATE
10024 BABY TOP 750 F03 07-APR-07
> “2008-Dec-31”;
10090 TULIP SKIRT 850 F02 31-MAR-
07
Page 6 Sample Paper 1 Computer Science Class 12

29. Write a user defined function change(L) to accept (g) Pop()


a list of numbers and replace the number in the (h) Pop()
list with its factorial.
Sol :
Example :
Input : [3,4,5,6,7]
Output: [6, 24, 120, 720, 5040]
Sol :
L = []
n = int (input(“Enter number of
elements”))
for i in range (1, n + 1):
b = int (input (“Enter element:”))
L append (b)
j=0
for a in L:
f=1
for, i in range(1,( a+1)):
Section D
f=f*i
31. Granuda consultants are setting up a secured
L[j]=f
network for their office campus at Faridabad for
j+=1
their day-to-day office and web based activities.
print(L)
They are planning to have connectivity between 3
30. Suppose STACK is allocated 6 memory locations buildings and the head office situated in Kolkata.
and initially STACK is empty (Top = 0). Given Answer the questions (i) to (v) after going through
the output of the program segment: the building positions in the campus and other
AAA = 4 details, which are given below:
BBB = 6 Distance between various buildings
Push (STACK, AAA)
Building RAVI to Building JAMUNA 120 m
Push (STACK, 4)
Building RAVI to Building GANGA 50 m
Push (STACK, BBB +2)
Push (STACK, AAA + BBB) Building GANGA to Building JAMUNA 65 m
Push (STACK, 10) Faridabad Campus to Head Office 1460 km
while (Top>0):
Element = STACK.Pop( ) Number of computers
print(Element)
Building RAVI 25
Sol :
Building JAMUNA 150
Output
10 Building GANGA 51
10 Head Office 10
8 (i) Suggest the most suitable place (i.e. block)
4 to house the server of this organisation.
4 Also, give a reason to justify your suggested
or location.
Consider the following operations are done on a (ii) Suggest a cable layout of connections between
stack. What will be the final status of the stack the building inside the campus.
after all the operations are performed. (iii) Suggest the placement of the following devices
(a) Push(True) with justification:
(b) Push(False) (a) Switch (b) Repeater
(c) Push(10) (iv) The organisation is planning to provide a
(d) Pop() high speed link with its head office situated in
(e) Push(50) the Kolkata using a wired connection. Which
(f) Push(70)
Page 7 Sample Paper 1 Computer Science Class 12

of the following cable will be most suitable for fetchone() method?


this job? (ii) What will be the datatype of Mydata
(a) Optical fibre (b) Co-axial cable object after the given command is
(c) Ethernet cable executed?
(v) Consultancy is planning to connect its office
Sol :
in Faridabad which is more than 10 km from
Head office. Which type of network will be (a) The error is run time error:
formed? x = int(input(“Enter the value of
x : ”))
Sol : y = int(input(“Enter the value of
(i) The most suitable place to house the server is y :”))
JAMUNA because it has maximum number if (y! = 0):
of computers. z = x/y
(ii) print(“The value of z : ”, z)
(b) (i) fetchone( ) method retrieves the next row
of a query result set and returns a single
sequence, or none if no more rows are
available. So one record will be returned
by fetchone( ) method.
(ii) tuple is the datatype of Mydata object
after the given command is executed.
Tuples are used to store heterogeneous
elements, which are elements belonging
to different data types.
(iii) (a) Switches are needed in every building to
or
share bandwidth in every building.
(a) Predict the output :
(b) Repeaters may be skipped as per above
str = “Python Program”
layout, (because distance is less than 100
def sTringoutput(str):
m) however, if building RAVI and building
print(str[3:5])
JAMUNA are directly connected, we can
print(str[–10])
place a repeater there as the distance
print(str[5:])
between these two buildings is more than
print(str[–28])
100 m.
(b) Define fetchmany([size]). How does fetchone()
(iv) (b) Co-axial cable
method differ from fetchall() method?
(v) MAN
Sol :
32. (a) The code given below will give an error on
(a) ho
execution. Identify the type of the error and
modify the code to handle such type of an ‘O’
error. n Program
x = int(input(“Enter the value of
x : ”)) IndexError
y = int(input(“Enter the value of (b) fetchmany([size]) returns the number of rows
y : ”)) specified by the size argument. When called
z = x/y repeatedly this method fetches the next set
print (“The value of z : ”, z) of rows of a query result and returns a list
(b) Note the following to establish the connection of tuples. If no more rows are available, it
between Python and MySQL: returns an empty list.
A resultset is extracted from the database fetchone () method returns the next row from
using the cursor object (that has been already the result set as tuple while fetchall () fetches
created) by giving the following statement. all the rows of a query result.
Mydata=cursor.fetchone( )
(i) How many records will be returned by
Page 8 Sample Paper 1 Computer Science Class 12

33. What are the advantages of CSV files? (ii) There is no distinction between text and
Write a python program using following functions numeric values
to : Program:
A file “teacher.csv” contains a city, teacher name import csv
and Salamount. def addTransaction ( ):
(a) Search() : Search and print all rows where f1 = open (“bank.csv”,‘w’,
city is “delhi”. newline = “\n”)
Sample “teacher.csv” : w1 = csv.writer(f1, delimiter
= “\t”)
City Teacher Name Salamount w1.writerow([‘TranID’,
Delhi, Anil Sharma, 10000 ‘TranDate’, ‘Amount’, ‘Type’])
while True:
Pune, Mr Dua, 20000
op = int(input(“Enter 1 to add
Delhi, Mr Das, 25000 and 0 to exit”))
(b) Searchfromfile() : From the file “teacher.csv” if(op == 1):
print all rows where teacher name is “Anil”. TranID = int(input(“Enter
transaction ID: ”))
Sol :
Trandate = input(“Enter date:
Advantages of CSV: ”)
(i) CSV is faster to handle Amount = int(input(“Enter
(ii) CSV is smaller in size and is easy to generate amount: ”))
Program : Type=input(“Enter transaction
import csv type : ”))
def Search(): w1.writerow([TranID, Trandate,
f = open(“teacher.csv”, ‘r’) Amount, Type])
r = csv.reader(f, delimiter = ‘,’) elif op == 0:
for row in r : break
if row[0].lower()==”delhi: f1.close()
print(row[1], row[2]) def getTran():
f.close() f = open(“bank.csv”, ‘r’)
def Searchfromfile(): r = csv.reader(f, delimiter = ‘,’)
f = open(“teacher.csv”, ‘r’) for row in r :
r = csv.reader(f, delimiter = ‘,’) if “Deposit” in row[3] :
for row in r : print(row)
if “Anil” in row[1] : f.close()
print(row[1], row[2]) addTransaction()
f.close() getTran()
Search()
Searchfromfile()
or Section E
What are the Disadvantages of CSV files?
Write a program using functions :
34. Consider the following table Student:
(a) addTransaction() : To append bank
transactions of following structure to “bank. Table : Student
csv”
AdmNo RollNo Name Class Marks
TranlD TranDate Amount Type
(b) getTran() : To display those transactions 2715 1 Ram 12 90
whose type is “Deposit”. 2816 2 Shyam 11 95
Sol : 2404 3 Ajay 10 92
Disadvantages of CSV files are 2917 4 Tarun 12 94
(i) There is no standard way to represent the
(i) Can we make Class as the Primary key of the
binary data
table?
Page 9 Sample Paper 1 Computer Science Class 12

(ii) What is the cardinality of the table? Sol :


(iii) Write statements to : (i) pickle
(a) Display the average Marks . (ii) roomid, cname, days
(b) Display the different Classes . (iii) pickle.dump(hotellst,f)
or (Option for part (iii) only)
Write statements to :
(a) Change the data type of Marks column so
that it can take fractional values upto 2 END
decimals .
(b) Increase width of Name column to
varchar(50).
Sol :
(i) No , as the column carries duplicate values
and primary must be unique.
(ii) 4, Cardinality is the number of rows in a
table.
(iii) (a) SELECT AVG( Marks) FROM
Student;
(b) SELECT DISTINCT Class FROM
Student;
or
(a) ALTER TABLE Student MODIFY
Marks float(8,2);
(b) ALTER TABLE Student MODIFY Name
varchar(50);

35. The code given below opens a binary file and


writes records of customer’s roomid, Name and
days of stay . Some of the codes are missing .Write
codes to fill up the blanks :
import....... # Blank1
hotellst=[]
cname=“ ”
days=0.0
roomid=0
ans=‘y’
f=open(“hotel.dat”, “wb”)
print(“Welcome to my Hotel ”)
while ans== ‘y’:
roomid=input(“Enter Roomld :”)
cname=input(“Enter Customer name
:”)
days=float(input(“Enter days of
stay :”))
hotellst=[...., ....., .....]
# Blank2 To create the record to
be written .........# Blank3 To
write the data to the binary file.
ans=input(“Continue(y/n)”)
f.close()
(i) Write the missing code for Blank1.
(ii) Write the missing code for Blank2.
(iii) Write the missing code for Blank3.
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 5 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. Given : s= “ComputerExam”. What will be the


Section A output of
print(s[2]+s[8]+s[1:51)?
1. _____command modifies or change the existing (a) mEOMUU (b) mEompu
records in a table. (c) mEomPU (d) MEompu
(a) UPDATE
Sol :
(b) CHANGE
(c) ALTER (b) mEompu
(d) MODIFY
6. State True or False
Sol : Digits are one of the parts of the Python character
(a) UPDATE set
Sol :
2. Which of the following operator cannot be used
with string data type? True
(a) + (b) in
(c) * (d) / 7. The clause to arrange the data of a column in
descending order is
Sol : (a) DESC (b) GROUP BY
(d) / (c) LIKE (d) ASC
Sol :
3. Which of the following is a category of SQL
commands? (a) DESC
(a) DDL (b) TCL
(c) DML (d) All of these 8. Which of the following are the most obvious kind
of constants?
Sol : (a) Keywords (b) Literals
(d) All of these (c) Variables (d) Identifiers
Sol :
4. What is the output of the following code?
num = 4 + float (7)/int (2.0) (b) Literals
print (“num =”, num)
(a) num = 7.5 (b) 7.5 9. Which of the following types of files will need the
(c) num : 7.5 (d) Error pickle module for working on it ?
(a) Binary files (b) Text files
Sol : (c) CSV files (d) All of these
(a) num=7.5 Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(a) Binary files 15. Which of the following functions will read lines of
a text file as list elements.
10. In the following code, which lines will give error? (a) read( )
(Assume the lines are numbered starting from 1.)
(b) get()
mul=3
value=10 (c) readline( )
for i in range (1, 6, 1): (d) readlines( )
if (value % mul = 0): Sol :
print (value * multiply)
else (d) readlines( )
print (value + multiply)
16. Which of the following will be the output of the
(a) 4,5
statement given below?
(b) 4,5,6
print([12,34,56,78,90].pop())
(c) 4,5,6,7
(a) 78 (b) 90
(d) No errors
(c) 12 (d) 12,34,56,78,90
Sol :
Sol :
(c) 4,5,6,7
(b) 90
11. There can be____foreign keys in a relation.
Direction (Q.Nos. 17-18) are Assertion and
(a) 2 (b) 3
Reason based questions.
(c) 1 (d) Multiple
Sol : 17. Assertion (A) In a cross join the number of records
in the output will be the maximum.
(d) Multiple
Reason (R) A cross join is also called a Cartesian
12. The_____clause with the COUNT() function product.
counts only the unique values in an attribute. (a) Both A and R are true and R is the correct
(a) UNIQUE explanation for A.
(b) HAVING (b) Both A and R are true but R is not the
(c) DISTINCT correct explanation for A.
(d) LIKE (c) A is true but R is false.
Sol : (d) A is false but R is true.
(c) DISTINCT Sol :

13. User can write Python script using (b) Both A and R are true but R is not the correct
(a) MySQL.connector library explanation for A.

(b) SQL.connect library 18. Assertion (A) A file that is opened using the
(c) MySQL.connect library open() function may not specify the mode of
opening it.
(d) None of these Reason (R) If the mode is not specified , the read
mode is used by default..
Sol :
(a) Both A and R are true and R is the correct
(a) MySQL.connector library explanation for A.
14. _____is a protocol used for remote login. (b) Both A and R are true but R is not the
(a) HTIT correct explanation for A.
(b) PPP (c) A is true but R is false.
(c) IRCP (d) A is false but R is true.
(d) Telnet
Sol :
Sol :
(b) Both A and R are true but R is not the correct
(d) Telnet explanation for A.
Page 3 Sample Paper 1 Computer Science Class 12

Section B 23. (a) Write the full forms of :


(i) POP (ii) HTTP
(b) Differentiate between the terms Internet and
19. Observe the given list and find the answer of
Intranet.
questions that follows.
list1 = [23, 45, 63, ‘Hello’, 20 Sol :
‘World’, 15, 18] (a) (i) Post Office Protocol.
(i) list1[–3] (ii) list1[3] (ii) HyperText Transfer Protocol
Sol : (b) Differences between Internet and Intranet are
as follows
(i) ‘World’ (ii) ‘Hello’
Internet Intranet
20. What is the advantage of using switch over hub?
Access by an individual Access by only
Sol : with dial-up access. authorised employees.
Switch provides a dedicated line at full bandwidth Information on Information on
between two devices but hub doesn’t provide a Internet could be Intranet could be
dedicated line. Hub share the bandwidth. general, public and specific, corporate and
or advertisement. proprietary.
Write some benefits of networking.
24. Predict the output
Sol :
dic = {‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4}
Some of the benefits of networking are print(dic)
(i) File sharing if ‘a’ in dic :
(ii) Hardware sharing del dic[‘a’]
(iii) Application sharing print(dic)
(iv) User communication
Sol :
(v) Access to remote database
Output
21. (a) Find the output {‘d’ : 4, ‘a’ : 1, ‘c’ : 3, ‘b’ : 2}
L = [10, 19, 45, 77, 10, 22, 2] {‘d’ : 4, ‘c’ : 3, ‘b’ : 2}
(i) L [3 : 5] (ii) L [: : –2] or
(b) Find the error(s). Distinguish between tuple and list.
L1 = [7, 2, 3, 4]
L2 = L1 + 2 Sol :
L3 = L1 * 2 Differences between tuple and list are as follows
L = L1.pop(7) Tuple List
Sol : Elements of a tuple are Elements of a list are
immutable. mutable.
(a) (i) [77, 10] (ii) [2, 10, 45, 10]
Tuple is declared in List is declared in square
(b) Error 1 L2 = L1 + 2 because + operator
parenthesis 0. brackets .
cannot add list with other type as number or
Tuples cannot be changed Lists can be changed after
string. after creation. creation.
Error 2 L = L1.pop(7) parentheses puts index
Iterating over the elements Iterating over the elements
value instead of element. In the given list, of a tuple is fast. of a list is slow.
maximum index value is 3 and 7 is out of
index range. 25. Explain the concept of candidate keys with the
help of an appropriate example.
22. What do you understand by RDMS?
Sol :
Sol :
A candidate key is a set of one or more fields that
A Relational Database Management System identifies each record uniquely in a table. There
(RDBMS) is a database management system. It can be multiple candidate keys in one table and
is developed by Dr. E.F. Codd, of IBM’s SAN one of them will become the primary key.
Jose Research Laboratory. e.g.
Page 4 Sample Paper 1 Computer Science Class 12

Table : Item trains.


(b) Considering the tables Train and Travel given
INO IName Qty
above write commands for the following :
101 CD 10 (i) Display passenger names , corresponding
102 Pen 5 train names and amounts for records
where amount >5000.
103 Pencil 2
(ii) Increase amount of passengers by 20%
104 Eraser 3 who are travelling by ‘AC”
In the Item table, INO and IName can be treated (iii) Display a cross join of the two tables.
as the candidate keys. (iv) Remove records of passengers who are
or travelling by “Rajdhani”.
Observe the following table carefully and write
Sol :
the names of the most appropriate columns,
which can be considered as (i) candidate keys and (a) SELECT Tr.Pname, T.Tname FROM
(ii) primary key. Travel Tr, Train T WHERE Tr.TId =
Table: Product
T.TId AND Tname LIKE “%Mail”;
(b) (i) SELECT T1.Pname,T2. Tname,
CID CNAME AMOUNT COUNTRY ITEM
T1.Amt FROM Travel T1, Train
101 ALLE 100000 JMEKA SHOES T2 WHERE T1 .TId= T2. TId AND
111 BEN 20000 FRANCE HELMET Amt>5000;
110 RIKI 25000 AMERICA BAG (ii) UPDATE Travel SET
Amt=Amt+Amt*0.2 WHERE Class=
011 BRETT 105000 AUSTRALIA BAT
LEE “AC”;
(iii) SELECT*FROM Travel,Train;
Sol : (iv) DELETE FROM Travel Tr, Train
(i) Candidate Keys CID, ITEM T WHERE Tr.TId = T.TId AND
(ii) Primary key CID T.Tname=“Rajdhani”;

27. A binary file “emp.dat” contains records of


employees as per following structure:
Section C Eno Ename Salary
1 Mr. Raj 85000
26. (a) Consider the tables Travel and Train given
h
below.
Write a program in Python to open the Binary
Table : Travel file “emp.dat” and display only those records
where the employee salary is greater than 75000.
Tcno Pname Class TId Amt
Sol :
1 Rahul AC T1 2500
import pickle
2 Sujit SL T2 4500
f=open(“emp.dat”, “rb”)
3 Ravi AC T1 6000 while True:
4 Ankita AC T3 1800 try:
1st=pickle.load(f)
if (lst[2]>75000):
Table : Train
print(“Employee No. :”, 1st[0])
TId Tname print(“Employee Name :”, 1st[1])
T1 Rajdhani print(“Employee Salary :”,
1st[2])
T2 Himgiri Exp except EOFError:
T3 Darjeeling Mail print(“No more records”)
break
Write the command to display the passenger
f.close()
names and the train names by which they are
or
travelling for all passengers travelling by “Mail”
Page 5 Sample Paper 1 Computer Science Class 12

Write a program to read the content from a text ND50 T Prasad 122-K, SDA New Delhi
file “status.txt”, count and display the total
number of lines and blank spaces present in it. TABLE: RECIPIENT
e.g. if the “status.txt” file contains the following
RecID SenderlD RecName RecAddress RecCity
lines:
Welcome to your one-step solutions for all your KO05 ND01 R Bajpayee 5, Central Kolkata
Avenue
study, practice and assessment needs for various
competitive & recruitment examinations and ND08 MU02 S Mahajan 116, A Vihar New
Delhi
school segment. We have been working tirelessly
for over a decade to make sure that you have MU19 ND01 H Singh 2A, Andheri Mumbai
East
best in class study resources because you deserve
SUCCESS AND NOTHING LESS... MU32 MU15 P K Swamy B5, C S Mumbai
Terminus
The output will be:
The status file contents are ND48 ND50 S Tripathi 13, B1 D, New
Mayur Delhi
Total lines in file are: 4 Vihar
Total spaces in file are: 43
(i) To display the names of all Senders from
Sol : Mumbai.
import os (ii) To display the RecID, SenderName,
tfile=‘status.txt’ SenderAddress, RecName, RecAddress
if os.path.isfile(tfile): for every Recipient.
fob=open(tfile, ‘r’) (iii) To display Recipient details in ascending
blankspaces=total_lines=0 order of RecName.
print(“The status file contents (iv) To display number of Recipients from
are”). each City.
print(“_____”) (b) Display the Sender name and corresponding
while True: Recipient name from the tables where sender
aline=fob.readline() is from “NEW DELHI” and recipient is from
if not aline: “KOLKATA”.
break Sol :
else:
(a) (i) SELECT SenderName FROM SENDER
total_lines=total_lines+1
WHERE SenderCity = ‘Mumbai’;
aline=aline.rstrip()
(ii) SELECT RecID, SenderName,
for i in aline:
SenderAddress, RecName,
if i.isspace():
RecAddress
blankspaces=blankspaces+1
FROM RECIPIENT, SENDER WHERE
print(“Total lines in file are:
RECIPIENT.SenderlD = SENDER.
%d” %total_lines)
SenderID;
print(“Total space in file are:
(iii) SELECT *FROM RECIPIENT ORDER
%d” % blankspaces)
BY RecName;
fob.close()
(iv) SELECT COUNT(*) AS “No. of
else:
Recipients”, RecCity FROM
print(“File does not exist”)
RECIPIENT GROUP BY RecCity;
28. (a) Consider the following tables SENDER and (b) SELECT SenderName, RecName
RECIPINT. Write SQL commands for the FROM Sender S , Recipient R
statements (i) to (iv). WHERE S.SenderlD=R.SenderID AND
(SenderCity= “New Delhi” AND
TABLE: SENDER RecCity=“KOLKATA”);
SenderlD SenderName SenderAddress SenderCity
29. Write a user defined function change(L) to accept
ND01 R Jain 2, ABC Appts New Delhi
a list of numbers and replace the numbers in the
MU02 H Sinha 12, Newtown Mumbai
list with their sum of digits.
MU15 S Jha 27/A, Park Street Mumbai Example
Page 6 Sample Paper 1 Computer Science Class 12

Input : [32,142,215,26,7]
Output : [5, 7 , 8 , 8, 8,7]
Sol :
L= [ ]
n=int(input(“Enter number of
element”))
for i in range (1, n+1):
b=int(input(“Enter element:”))
L=append(b)
i=0
for a in L:
s=0 Section D
while a>0:
s+=a%10 31. Freshminds University of India is starting its first
a//=10 campus in Ana Nagar of South India with its
L[i]=s centre admission office in Kolkata. The university
i+=1 has three major blocks comprising of Office block,
print(L) Science block and Commerce block is in 5 km area
campus.
30. Write Push (contents) and Pop() methods in
As a network expert, you need to suggest the
Python to add numbers and remove numbers
network plan as per (i) to (v) to the authorities
considering them to act as Push and Pop
keeping in mind the distance and other given
operations of stack.
parameters.
Sol :
def Push (contents):
if(len(stack) >= limit):
print(“Stack Overflow!”)
else :
stack.append (contents)
print (“Stack after Push”, stack)
def Pop( ):
if (len (stack) <= 0):
print(“Stack Underflow!”) Expected wire distance between various locations.
return 0 Office Block to Science Block 90 m
else : Office Block to Commerce Block 80 m
return stack.Pop( )
Science Block to Commerce Block 15 m
or
Kolkata Admission Office to Ana Nagar 450 km
Find the final contents of a stack on which the
Campus
following operations are done.
Expected number of computers to be installed at
1. Push(100)
various locations in the university are as follows:
2. Push(200)
Office Block 10
3. Push(50)
Science Block 140
4. Push(50) Commerce Block 30
5. Pop() Kolkata Admission Office 8
6. Push() (i) Suggest the authorities, the cable layout
7. Pop(2) amongst various blocks inside university
campus for connecting the blocks.
8. Pop() (ii) Suggest the most suitable place (i.e. block)
to house the server for this university with a
Sol :
suitable reason.
Page 7 Sample Paper 1 Computer Science Class 12

(iii) Suggest an efficient device from the following :”))


to be installed in each of the block to connect a = x +y+ z
all the computers. print (“Result = ”, a)
(a) Modem (b) Switch (c) Gateway (b) import mysql.connector
(iv) Suggest a suitable topology to connect the mycon = mysql.connector.connect (
computers in each building. host = “local host”,
(v) University is planning to connect its campus user = “root”,
in Kolkata which is more than 100 km. Which passwd = “system”,
type of network will be formed? database = “School”)
cursor = mycon.cursor( )
Sol : db = cursor .execute
(i) (“CREATE TABLE Student(
Roll No Int( 5) Primary key,
FirstName varchar(30) NOT NULL,
LastName varchar(30),
Address varchar(50),
ContactNo varchar(20)
Marks Float,
Course char(20),
Rank char(10) check (Rank IN(‘Good’
(ii) The most suitable place to house the server ,‘Best’,‘Bad’,‘Worst’,‘Average’))))
is Science Block as it has maximum number mycon.close ( )
of computers. Thus, reducing the cabling cost or
and increases efficiency of network. (a) Differentiate between a logical error and
(iii) (b) Switch is the device to be installed in each syntax error. Also, give suitable examples of
of the blocks to connect all the computers. each in Python.
(iv) Star topology, as it is the best in efficiency. (b) What is the use of fetchone() method? Write
(v) WAN (Wide Area Network) will be formed. an example code to fetch a single record from
a database.
32. (a) Underline the syntax errors in the following
Note :
program Database : PythonDB
x = int(input(“Enter first number:))
Table : Student
Host : localhost
y = int(input(“Enter second number:”))
z = int(input(“Enter third number:”) UsedlD : root
Password : arihant
a = x+ b+ z
print (“Result = ”, b)
(b) Write the code to create the following table Sol :
Student with the following fields (a) Differences between logical error and syntax
RollNo error are as follows:
FirstName
Logical Error Syntax Error
LastName
Address
ContactNo It occurs because of It occurs when
Marks wrong implementation statements are wrongly
Course of logic. written violating rules
Rank of the programming
In the table, Rank should be Good, Best, language.
Bad, Worst, Average. With logical errors, the With syntax errors,
Sol : code is syntactically the code is not
correct and compiler syntactically correct
(a)
will not show any error and compiler will show
x = int(input(“Enter first number:”))
message. the error messages.
y = int(input(“Enter second number:”))
z = int(input(“Enter third number
Page 8 Sample Paper 1 Computer Science Class 12

w1 = csv.writer(f2)
It produces the output, It does not produce
for row in r1 :
but undesired. any output.
w1.writerow(row)
e.g. in place of e.g. in place of f1.close()
(c = a * b); if by (a == b); if by mistake f2.close()
mistake (a == b); is written, it def convertcsv():
(c = a + b); is written, will be a syntax error. f1 = open(“old.csv”,‘r’)
it will be a logical f2 = open(“converted.csv”, ‘w’,
error. newline = “\n”)
(b) fetchone() returns the next row from the r1 = csv.reader(f1, delimiter =
result set as tuple. If there are no more rows “:”)
to retrieve, None is returned. w1 = csv.writer(f2, delimiter =
e.g. To fetch only one record “;”)
import mysql.connector for row in r1:
con = mysql.connector.connect w1.writerow(row)
(host = “localhost”, f1.close()
user = “root”, f2.close()
passwd = “arihant”,database addcsv()
= “PythonDB”) convertcsv()
cursor = con.cursor() or
try: CSV files are opened with which argument
cursor.execute(“Select Name, to suppress EOL translation. Write a python
RollNo, Address, Percentage from program to perform the following using functions
Student”) as follows :
display = cursor.fetchone() (a) copytocsv() :
print(display) A CSV file “marks.csv” has name, class and
except: marks separated by comma. Write the Python
con.rollback() function to copy only the name and class to
con.close() another CSV file “class.csv”.
(b) copyselected() :
33. Which module is used to operate on CSV file? The CSV file “marks.csv” which has name,
Write a python program with following functions class and marks separated by comma. Write
: the Python function to copy only rows of
(a) addcsv(): students of class 2 to another CSV file “class.
File old.csv has come from branch in Pune csv”.
and it needs to be added to file “updated.
csv” which has data for all branches. Write Sol :
the code in the function to perform the same. newline= ‘ ’
(b) convertcsv() : Program:
A file old.csv has come with separator ‘:’ but import csv
your system can only read ‘;’ Write a program def copytocsv():
to convert to “converted.csv” file. Write the file = open(‘class.csv’,‘w’,
function to change the separator of the file. newline=“ ”)
Sol : writer = csv.writer(file)
with open(‘marks.csv’) as csvfile:
To read and write in CSV files we need to import data = csv.reader(csvfile)
csv module. for row in data:
Program: writer.writeraw(row[0],
import csv row[1]])
def addcsv(): file.close()
f1 = open(“old.csv”, ‘r’) def copyselected():
f2 = open(“updated.csv”, ‘a’, file = open(‘class.csv’, ‘w’,
newline = “\n”) newline= “\n”)
r1 = csv.reader(f1) w1 = csv.writer(file)
Page 9 Sample Paper 1 Computer Science Class 12

with open(‘marks.csv’) as csvfile: print(filedata)


data = csv. reader(csvfile) data=filedata.split(‘ ’)
for row in data: for.......... in data : #Blank1
if row[1]== ‘2’: if words[–1] in “aeiou” and ...in
writer.writerow(row) “AEIOU”: # Blank2
file.close() print(......... .) # Blank3
copytocsv() f.close()
copyselected() (i) Write the missing code for Blank1.
(ii) Write the missing code for Blank2.
(iii) Write the missing code for Blank3.
Section E Sol :
(i) words
34. Consider the following table Person
(ii) words[0]
P_Id LastName First Name Address City (iii) words
1 Hansen Ola Timoteivn Sandnes
10
2 Svendson Tove Borgvn 23 Sandnes
END
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger

(i) What should be the constraint(s) of the P_Id


column?
(ii) If 3 columns are added to the table , what will
be its degree?
(iii) Write statements to :
(a) Display the Unique Cities.
(b) Display Firstnames of people who do not
have a address.
or (Option for part (iii) only)
Write appropriate data types to store the
following :
(a) Amounts carrying values with decimal.
(b) Joining dates.
Sol :
(i) Primary key
(ii) 8, There are 5 columns + 3 = 8 columns.
Degree is number of columns.
(iii) (a) SELECT DISTINCT City FROM
Person;
(b) SELECT FirstName FROM Person
WHERE address IS NULL;
or
(a) float/decimal/double
(b) date/datetime

35. The code given below reads a text file and displays
those words that begin with an uppercase vowel
and end with a lowercase vowel . Some of the codes
are missing .Write codes to fill up the blanks.
f=open(“emp.txt”)
filedata=f.read()
count=0
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 6 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. ............are drawn using certain special purpose


Section A symbols.
(a) Algorithm (b) Pseudocode
1. The output of the code will be : (c) Flowchart (d) Decision table
L=[6,7,8,9,10]
Sol :
print(L[2:20])
(a) [8, 9, 10] (b) [ ] (c) Flowchart
(c) Error (d) [6,7,8,9,10]
6. To arrange a table in descending order of field
Sol : Salary the clause to be used is
(a) [8, 9, 10] (a) Order by Salary
(b) Order by Salary Desc
2. The random function returns a random value (c) Arrange by SalaryDesc
between (d) Arrange by Salary
(a) 1 and 10 (b) 0 and 10
Sol :
(c) 0 and 1 (d) 1 and 100
(b) Order by Salary Desc
Sol :
(c) 0 and 1 7. The BETWEEN clause can not be used for
(a) Integer Fields (b) Varchar Fields
3. To read three characters from a file object f, we (c) Date Fields (d) None of these
use..........
Sol :
(a) f.read(3)
(b) f.read() (d) None of these
(c) f.readline() 8. The constraint that ensures that the field does
(d) f.readlines() not get any NULL values is
(a) NULL (b) PRIMARY KEY
Sol :
(c) CHECK (d) NOT NULL
(a) f.read(3)
Sol :
4. State True or False (d) NOT NULL
“The pop() method removes and displays the last
element of a list.” 9. is and is not are_____Operators.
(a) Membership (b) Identity
Sol :
(c) Logical (d) Comparison
True
Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(b) Identity 15. To open a text file for adding records keeping the
existing records the mode should be
10. What will the following code display? (a) ab (b) xb
name = “Neha” (c) rb (d) w+
type (name)
(a) Invalid function <type> Sol :
(b) <class ‘str’> (d) w+
(c) <class ‘int’>
(d) <class ‘float’> 16. A device that connects two dissimilar networks is
(a) Modem
Sol : (b) Repeater
(b) <class ‘str’> (c) Bridge
(d) Gateway
11. Which of the following is not required while
Sol :
specifying the connection string in database
connection? (d) Gateway
(a) Host
Directions : (Q.Nos. 17-18) are Assertion and
(b) Table name Reason based questions.
(c) Username
(d) Password 17. Assertion (A) Binary files are processed faster
than text files.
Sol : Reasoning (R) They are written in Binary format
(b) Table name and are more close to the computer.
(a) Both A and R are true and R is the correct
12. The ALTER TABLE command belongs to............. explanation for A.
category (b) Both A and R are true and R is not the
(a) DML (b) TCL correct explanation for A.
(c) DDL (d) DCL
(c) A is true but R is false.
Sol :
(d) A is false but R is true.
(c) DDL
Sol :
13. Which of the following are possible relational
operations? (a) Both A and R are true and R is the correct
(a) Join explanation for A.

(b) Selection 18. Assertion (A) A function that is neither built in


(c) Cartesian product nor modular must be defined.
Reason (R) The code of built in and modular
(d) All of these functions are available for the Python compiler
, but if the function is not defined anywhere the
Sol :
compiler cannot get the code.
(d) All of these (a) Both A and R are true and R is the correct
explanation for A.
14. Given a tuple tup = (20,50,10,60,30). The
statement append(90) returns (b) Both A and R are true and R is not the
(a) (20,50,10,60,30,90) correct explanation for A.
(b) (90) (c) A is true but R is false.
(c) Error (d) A is false but R is true.
(d) (30,90) Sol :
Sol : (a) Both A and R are true and R is the correct
explanation for A.
(c) Error
Page 3 Sample Paper 1 Computer Science Class 12

Section B 23. (a) Write the full forms of


(i) HTML
19. Observe the code given below and find the output. (ii) HTTPs
s=“OceanView” (b) Write any two advantages of tree topology.
print(s[8] +s[2:] +str(len(s)))
Sol : Sol :

‘weanView9’ (a) (i) HyperText Markup Language


S[8] returns the character at index 8 . s[2:] returns (ii) HyperText Transfer Protocol secure
characters from index 2 to the end . len(s) returns (b) (i) The other nodes in a network are not
the number of characters in the string. All are affected if one of their nodes gets damaged
concatenated together by + or does not work.
20. What is the purpose of switch in a network? (ii) Tree topology provides easy maintenance
or and easy fault identification can be done.
Write names of few network devices.
Sol : 24. What output will the following code produce?
empdict={‘Eno’:[1,2,3,4], ‘Ename’ :
A switch is a networking device, which is used [‘Raj’, ‘Seema’, ‘John’, ‘Smith’],
to connect different LAN segments of a network. ‘Sal’:[10000, 20000, 30000, 40000]}
A switch also supports packet filtering and print(empdict[‘Ename’][0],
forwarding between LAN segments. empdict[‘Sal’][0])
or or
(i) Hub Write any two differences between Dictionary and
(ii) Switch Tuple.
(iii) Repeater
(iv) Gateway Sol :
(‘Raj’, 10000)
21. (a) What is the output of below questions? or
l1 = [23, 45, 19, 77, 10, 22]
(i) l1.sort() Tuple Dictionary
(ii) max(l1) 1. Immutable 1. Mutable
(b) Find error in defination of the function given.
2. Ordered by index 2. Ordered by key.
def finderrors(x=20,y)
print(x+y*2) 25. Mention atleast three limitations of DBMS.
Sol : or
What are primary and alternate key in a database?
(a) (i) [10, 19, 22, 23, 45, 77] (ii) 77
Give suitable example to explain each.
(b) Error 1 : default parameters must be assigned
from right to left Sol :
Error 2 : Function defination is missing “:” Some limitations of DBMS are given below
Correction : (i) High cost DBMS requires various software,
def finderrors(x=20, y=10) : hardware and highly intelligent people for
print(x+y*2) operating and maintaining the database
system. It increases its cost.
22. List some commonly used DBMS software
(ii) Database Failure If database is corrupted
packages.
due to power failure or any other reason, our
Sol : valuable data may be lost or whole system
Some commonly used DBMS software packages stops.
are (iii) Data Quality With increased number of users
(i) MySQL (ii) Oracle accessing data directly. There are enormous
opportunities for users to damage data. So, it
(iii) Postgre (iv) DB2 is not easy to provide a strategy to support
(v) MS-SQL (v) Sybase multiple users to update data simultaneously.
Page 4 Sample Paper 1 Computer Science Class 12

or (iii) Display names and room types of


Primary key is a column or set of columns which customers whose charges are between
helps to identify row uniquely. 2000 and 3000.
e.g. In table Student, RollNo of all students are (iv) Display Names of customers who are
different. So, RollNo is a primary key helps to staying in “AC” rooms”
identify the information of all students uniquely.
Sol :
Alternate key is a column or set of columns that
can act as a primary key but not selected as a (a) SELECT H.Cname, R.RoomType FROM
primary key. Hotel H , Room R WHERE H.RoomId=R.
Roomld;
Table : Student (b) (i) CREATE TABLE Hotel(TId
AdmNo RollNo Name Marks varchar(5), CName varchar(20),
1000 1 Akash 85 RoomId char(4), DtofArrival
date, Charges int); INSERT INTO
1201 2 Neha 90 Hotel VALUES(“T1”,“Ritesh”,
850 3 Babita 70 “R1”, “2016-09-09”,1800);
(ii) SELECT Cname FROM Hotel WHERE
1255 4 Himanshu 75
DtofArrival > “2005-05-01”;
e.g. In table Student, RollNo and AdmNo of
(iii) SELECT Cname, RoomType
all students are different. Both of them can be
FROM Hotel H, ROOM R WHERE
selected as a primary key. Suppose, we have
H.ROOMID=R.ROOMID AND (Charges
selected RollNo as a primary key then AdmNo is
BETWEEN 2000 AND 3000);
called as alternate key.
(iv) SELECT H.Cname FROM Hotel H,
Room R WHERE H.RoomId=RoomId
AND RoomType=“AC”;
SECTION C
27. A binary file “data.dat” contains records of
26. Consider the tables Hotel and Room given below : students as per following structure :
Table : Hotel Ano Sname Marks
TId CName Roomld DtofArrival Charges 1 Raj 850
T1 Ritesh R1 2016-09-09 1800
h
T2 Sumana R2 2020-08-01 2000
h
T3 Abhi R3 1995-04-05 3000
Write a Program in Python to search for a student
T4 Ram R1 1994-02-02 2500
whose number/id is input by the user. If not found
T5 Nitin R2 NULL 7000 appropriate message should be displayed.
or
Table : Room Write a program with method countand ( ) to
count the word ‘and’ or And’ as an independent
RoomlD RoomType FLoor
word in a text file “status.txt”. e.g. if the content
R1 AC First of the file “status. txt” is as follows:
R2 Deluxe Second Welcome to your one-step solutions for all your
study, practice and assessment needs for various
R3 General Second competitive & recruitment examinations and
(a) Write a command to display the customer school segment. We have been working tirelessly
names and the types of rooms in which they for over a decade to make sure that you have
are staying. best in class study resources because you deserve
(b) With respect to the tables given above, write SUCCESS AND NOTHING LESS...
SQL commands for the following. Then the output of the program should be: Count
(i) Create the table hotel and insert the 1st of _and_ in file is/are: 3
record
Sol :
(ii) Display the details of customers who have
arrived after 01-05-2005 import pickle
Page 5 Sample Paper 1 Computer Science Class 12

fobj=open(“data.dat”,“rb”)
6 Ketaki 16 ENT 24/02/98 300 F
ano=input(“Enter student no. to
7 Ankita 29 Cardiology 20/02/98 800 F
search :”)
st1st=[] 8 Zareen 45 Gynaecology 22/02/98 300 F
found=0 9 Kush 19 Cardiology 13/01/98 800 M
while True: 10 Shailya 31 Nuclear 19/02/98 400 M
try: Medicine
st1st=pickle.load(fobj) (i) To show all information about the
if ano==st1st[0]: patients of Cardiology Department.
print(“Found”)
print(“Name :”, st1st[1]) (ii) To list the name of female patients, who
print(“Marks :”, st1st[2]) are in Orthopaedic Department.
found=1 (iii) To list names of all patients with their
break date of admission in ascending order.
except EOFError:
(iv) To display Patient’s Name, Charges, Age
print(“Not found”)
for male patients only.
break
if found==0: (b) Write the command to view all the tables in
print(“Search Unsuccessful ”) database.
fobj.close() Sol :
or
(a) (i) SELECT FROM HOSPITAL WHERE
import os
Department = ‘Cardiology’;
def countand():
if os.path.isfile(“status.txt”): (ii) SELECT Name FROM HOSPITAL
fob=open(“status.txt”, ‘r’) WHERE Department = ‘Orthopaedic’
c=0 AND Sex = ‘F’;
while True: (iii) SELECT Name FROM HOSPITAL
Str=fob.readline() ORDER BY Dateofadm;
if not Str:
break (iv) SELECT Name, Charges, Age FROM
Str=Str.rstrip().lower(). HOSPITAL WHERE Sex = ‘M’;
split() (b) Show tables
for i in range(len(Str)):
if (Str[i]==‘and’ or Str[i]== 29. Write user defined functions factors(num) and
‘AND’): factorial(num) to find the factors and factorial of
c=c+1 a number accepted from the user and passed to
print(“Count of_and_in file is/ the functions from main function.
are : ”,c) Sol :
else:
def factorial(num):
print(“File does not exist”)
f=1
countand()
for i in range(1,(num+1)):
28. (a) Write the SQL commands for (i) to (iv) on f*=i
the basis of the table HOSPITAL print(“Factorial :”,f)
def factors(num):
TABLE: HOSPITAL print(“Factors of ”,num)
No Name Age Department Date- Cha- Sex for i in range(1,(num+1)):
ofadm rges if num%i==0:
1 Sandeep 65 Surgery 23/02/98 300 M print(i)
2 Ravine 24 Orthopaedic 20/01/98 200 F def main():
3 Karan 45 Orthopaedic 19/02/98 200 M
n=int(input(“Enter a number :”))
factorial(n)
4 Tarun 12 Surgery 01/01/98 300 M
factors(n)
5 Zubin 36 ENT 12/01/98 250 M main()
Page 6 Sample Paper 1 Computer Science Class 12

30. Write the Push operation of stack containing Section D


person names. Notice that the name should only
accept characters, spaces and period(.) except
31. Quick Learn University is setting up its academic
digits. Assume that Pname is a class instance
blocks at Prayag Nagar and planning to set up
attribute.
a network. The university has three academic
or
blocks and one human resource Centre as shown
Find the final contents of a stack that encounters
in the diagram below:
the following tokens.
Assume that an operand is pushed to stack and
a binary operator pops two operands from stack
and pushes the result to the stack.
45, 30, + , 50, 80, +, +
Sol :
def insert():
name_pattern=re.compile
(r “[A-Za-zs.]”)
while True:
n = input (“Enter name:”)
while name_pattern.search (n): Centre to Centre distance between various blocks/
print (“Invalid name”) Centre is as follows:

Law Block to Business Block 40 m


print (“Enter name correctly”)
n = input()
Sname. append (n) Law Block to Technology Block 80 m
c = input (“Enter more name <y/n>” Law Block to HR Centre 105 m
.upper())
Business Block to Technology Block 30 m
if (c! = ‘y’);
break Business Block to HR Centre 35 m
or Technology Block to HR Centre 15 m
Scanned Operation Stack Number of computers in each of the blocks/centre
Elements Status are as follows:
45 Push 45 Law Block 15
30 Push 45, 30 Technology Block 40

+ Pop twice 45 + 30 = 75 HR Centre 115


75 Push Business Block 25

50 Push 75, 50 (i) Suggest the most suitable place (i.e. block/
Centre) to install the server of this university
80 Push 75, 50, 80 with a suitable reason.
(ii) Suggest an ideal layout for connecting these
+ Pop twice 50+ 80=130 75, 130
block/Centre for a wired connectivity.
+ Pop twice 130 + 205 (iii) Which device you will suggest to be placed/
75=205 installed in each of these blocks/Centre to
efficiently connect all the computers with in
Output 205 these blocks/Centre ?
(iv) The university is planning to connect its
admission office in the closest big city, which
is more than 250 km from university, which
type of network out of LAN, MAN or WAN
will be formed? Justify your answer.
(v) Expand the following
LAN
Page 7 Sample Paper 1 Computer Science Class 12

WAN Identifier Keyword


Sol : Identifier consists Keyword must consist
(i) The most suitable place to install the server any combination of only letters.
is HR centre. letters, numbers and
underscores.
It allows both It allows only lowercase
uppercase and except True, False and
lowercase. None.
e.g. x, sum 5, mul etc e.g. finally, continue,
yield etc.
(b) (i) Importing the API module
(ii) Acquiring a connection with database
(iii) Stored procedures and issuing SQL
statements
(iii) Switch
(iv) Closing the connection
(iv) WAN as it is another city.
(v) Local Area Network 33. What does csv writer() function do?
Wide Area Network Write a python program for operating on a csv
file “people.csv” using following functions :
32. (a) Underline the errors in the following code and
(a) addPeople() :To input details of people and
write the correct code :
add them to a csv file “people.csv” without
while s>0
removing the previous records. The record
if a%2=0
structure is as follows :
print(a%2)
AdhrNo Name City Age
elseif a%3=0 then
The file should store only those people whose
print(a%3)
age is greater than and equal to 18.
(b) What is database connectivity? How to create
(b) getPeople() : To open the file “people.csv”
a connection object?
and display records whose name starts with
or
“P”
(a) Differentiate between identifier and keyword.
or
(b) What conditions or terms are included by
What is the use of writerow() function?
BD-API?
A file “Toys.csv” exists storing details of toys
Sol : as per following structure :
(a) Corrected code : ToyID Toyname Category Cost
while s>0 : Write a program in python with functions as
if a%2==0 : follows
print(a%2) (a) addToy() : To append data of toys and
elif a%3==0 : store them to the file “Toys.csv” only if
print(a%3) the Toy category is “Boys”. Also display
(b) Database connectivity is an Application the number of toys added.
Programming Interface (API) which allows (b) showToys() : To open the file “Toys.csv”
the programmer to connect and interact with and display records of toys whose cost is
databases. above 1000.
connection_object = mysql. Sol :
connector.connect
The csv.writer() function returns a writer object
(host = HostName,
that converts the user’s data into a delimited
user = UserName,
string.
passwd = password)
This writer object can be used to write into CSV
or
files using the writerow() function.
(a) Differences between identifier and keyword
Program:
are
import csv
Page 8 Sample Paper 1 Computer Science Class 12

def addPeople() : Type YES!!!”)


with open(“people.csv”, “a”) as f: ch = input()
dt = writer(f) ch = ch.upper()
while True: if ch==“YES”:
ano= int(input(“Enter aadhar print(“––––––––”)
No:”)) else:
pname = input(“Enter person break
name:”) f.close( )
city = input(“Enter city:”) def showToys():
age = int(input(“Enter age:”)) with open(“Toys.csv”, ‘r’) as tfile:
dt.writerow([ano, pname, city, reader = csv.reader(tfile)
age]) for row in reader:
print(“Record has been added.”) if int(row[3])>1000:
print(“Want to add more record?Type print(row)
YES!!!”) tfile.close()
ch = input() addToy()
ch = ch.upper() showToys()
if ch==“YES”:
print(“––––––––”)
else: Section E
break
def getPeople(): 34. Consider the following table Cab :
with open(“people.csv”, ‘r’) as
file: Table : Cab
reader = csv.reader(file) CablD CabType Nop Rate
for row in reader:
if row[1][0]==‘P’: Cb1 Sedan 4 40
print(row) Cb2 Yellow Taxi 5 25
file.close()
Cb3 Mini 3 30
addPeople()
getPeople() Cb4 Micro 2 20
or (i) Which column qualifies to be the primary
writer.writerow(row) writes the row parameter key?
to the writer’s file object, formatted according to
(ii) Write a command to display the fields of the
delimiter defined in writer function
table along with their types and sizes.
Program:
import csv (iii) Write statements to :
def addToy(): (a) Add a new column Driver varchar(30)
with open(“Toys.csv”, “a”) as f:
(b) Change data type of Rate column to
dt = writer(f)
float(6,1).
tid=””
tname=”” (Option for part (iii) only)
cat=”” (a) To display the cab type whose rate is
cost=0 more than 25.
while True: (b) To display cab id and Number of
tid= int(input(“Enter toyid:”)) passengers for cab sedan.
tname = input(“Enter toy name:”)
cat = input(“Enter category:”) Sol :
cost= int(input(“Enter cost:”)) (i) Primary key : CabID
dt.writerow(tid, tname, cat, (ii) DESCRIBE Cab;
(iii) (a) ALTER TABLE Cab ADD Driver
cost])
print(“Record has been added.”) varchar(30);
(b) ALTER TABLE Cab MODIFY Rate
print(“Want to add more record?
Page 9 Sample Paper 1 Computer Science Class 12

float(6,1);
or
(a) SELECT CabType FROM Cab WHERE
Rate>25;
(b) SELECT CabID, Nop, FROM Cab
WHERE CabType = “Sedan”;

35. Riya wrote a program to search any string in text


file “school”. Help her to execute the program
successfully.
def check () :
datafile = open (.....)
found = input (“Enter any string to
be searched : ”)
f = False
for line in ....... :
if found in line :
f = .......
break
return f
f = check ()
if (f = =.......) :
print (“True”)
else :
print (......)
(i) Riya should open which file to search any
string?
(ii) Which value will assign to f in Line 7?
(iii) Fill the blank in Line 5.
Sol :
(i) school.txt
(ii) True
(iii) datafile

END
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 7 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

b = 1
Section A for a in range(1, 10, 2):
b += a + 2
1. Which of the following functions write data to a print(b)
binary file? (a) 31 (b) 33
(a) pickle() (b) writer() (c) 36 (d) 39
(c) load() (d) dump()
Sol :
Sol :
(c) 36
(d) dump()
6. Which of the following Python function displays
2. _____can be create using cursor( ) method of the memory id of a variable?
connection object. (a) type( ) (b) str( )
(a) Cursor object (b) Cursor variable (c) getid( ) (d) id( )
(c) Connect (d) None of these
Sol :
Sol :
(d) id( )
(a) Cursor object
7. Which of the following is an advantage of SQL?
3. _____command displays the contents of a (a) High speed
table. (b) Client/Server language
(a) DISPLAY (c) Easy to learn
(b) VIEW (d) All of these
(c) SELECT
Sol :
(d) SHOW
(d) All of these
Sol :
(c) SELECT 8. Which of the following operator performs an
integer division?
4. State True or False (a) * (b) //
Integer is a mutable data type in Python. (c) / (d) **
Sol : Sol :
False (b) //
5. Identify the output of the following Python 9. Predict the output of the following program:
statement: a = 5
Page 2 Sample Paper 1 Computer Science Class 12

b = a = 15 (a) read()
c = (a < 15)
print (“a = ”, a) 15. The cross join is also called
print (“b = ”, b) (a) Merging
print (“c = ”, c) (b) Cartesian product
(a) a=15 (b) a=15 (c) Natural join
b=15 b=10 (d) Equi join
c=False c=True Sol :
(c) a=15 (d) None of these
b=None (b) Cartesian product
c=False
16. ______is the base protocol for all application
Sol : protocols.
(a) a=15 (a) FTP
b=15 (b) TCP/IP
c=False (c) IRCP
(d) Telnet
10. Given s=“AISSE@2023”. What will be the output
of print(s[-1: :-1])? Sol :
(a) ‘3202@ESSIA’ (b) 3
(b) TCP/IP
(c) AISSE (d) ESSIA
Sol : Direction : (Q.Nos. 17-18) are Assertion and
Reason based questions.
(a) ‘3202@ESSIA’
17. Assertion (A)Pickling is a way to convey a Python
11. A primary key of a relation must be_____. object into character stream.
(a) UNIQUE only Reason (R) To perform pickling, the pickle module
(b) NOT NULL only needs to be imported.
(c) Both UNIQUE and NOT NULL (a) Both A and R are true and R is the correct
(d) Neither UNIQUE nor NOT NULL explanation for A.
Sol : (b) Both A and R are true but R is not the
(c) Both UNIQUE and NOT NULL correct explanation for A.
(c) A is true but R is false.
12. The........clause can group records on the basis of (d) A is false but R is true. A.
common values in a field.
(a) AGGREGATE (b) GROUP Sol :
(c) GROUP BY (d) JOIN (b) Both A and R are true but R is not the correct
Sol : explanation for A.
(c) GROUP BY 18. Assertion (A) A recursive function does not
require a loop.
13. The python function that adds a list at the end
Reason (R) A recursive function calls itself again
of another list is
and again until a certain condition is true.
(a) join() (b) add()
(a) Both A and R are true and R is the correct
(c) append() (d) extend()
explanation for A.
Sol : (b) Both A and R are true but R is not the
(d) extend() correct explanation for A.
(c) A is true but R is false.
14. Which of the following functions will read entire
(d) A is false but R is true.
contents of a text file?
(a) read() (b) readfull() Sol :
(c) readline() (d) readfile()
(a) Both A and R are true and R is the correct
Sol : explanation for A.
Page 3 Sample Paper 1 Computer Science Class 12

Sol :
Section B
Database The database is a shared collection
19. Observe the code given below and find the output of logically related data, designed to meet the
: information needs of an organisation. A database
s= “oceanview” is a computer based record keeping system whose
count=0 over all purpose is . to record and maintains
for a in s: information.
if a in “stuv”: DBMS A Database Management System (DBMS)
count+=1 is a collection of programs that enables users to
print(count) store, modify and extract information from a
database as per the requirements. It acts as an
Sol : interface between the application program and
1 the operating system to access or manipulate the
The for loop checks for existence of the characters database.
of the string in “stuv” , and returns the count. 23. (a) Write the full forms of :
(i) RJ45 (ii) XML
20. What is the difference between video conferencing (b) Write one advantages of Bus topology
and chat? compared to Star and one advantage of star
or topology compared to Bus.
What is WWW?
Sol :
Sol :
(a) (i) Registered Jack 45
Chat generally involves one-to-one communication. (ii) eXtensible Markup Language
On the other hand, video conferencing means more
(b) Advantage of Bus over star : Economically
than two persons are involved in a discussion.
better as a single backbone cable connects all
or
the computers.
WWW (World Wide Web) is a system of Internet
servers that supports hypertext and multimedia Advantage of Star over bus : Fault detection
to access several Internet protocols on a single and isolation is easy.
interface. This web standard allows programs on
24. What output will the following code produce?
many different computer platforms to properly
y=str(123)
format and display the information server.
x= “hello”*3
21. (a) Given the following code :
print(x,y)
d={‘Bed’:145000, ‘Almirah’:9000,
x=“hello” + “world”
‘Chair’:1000}
y=len(x)
for v in d.keys():
print(y,x)
if d[v]>100000:
or
d[v]– =10000
Write function names for the following with
print(d)
respect to strings.
What will be the output of the print statement?
(i) To make the first letter of a string in capital
(b) Write the value stored in the variable Num by
(ii) To find the index of the 1st occurrence of a
each of the following statements.
string in another
(i) Num = 2 * 3 – 4
(ii) Num = 2+3–1*3 Sol :
(iii) Num = (2+3)*2 hellohellohello 123
Sol : 10 helloworld
or
(a) {‘Bed’: 135000, ‘Almirah’: 9000, ‘Chair’:
(i) capitalize()- Returns a copy of the string with
1000}
the 1st character capitalized.
(b) (i) Num = 2
(ii) find() - Returns the lowest index in a string
(ii) Num = 2
where another string is found.
(iii) Num = 10

22. Explain database and DBMS in detail.


Page 4 Sample Paper 1 Computer Science Class 12

25. What is DDL? Explain with its commands. 3 5687 1


or
What is DML? Explain with its commands. 4 45000 1

Sol : 5 35000 15

DDL (Data Definition Language) provides With respect to the tables given above write a
statements for creation and deletion of the command to display the Lastname, Firstname
database tables, views, etc. The DDL provides a and corresponding order number arranged by
set of definitions to specify the storage structure Lastname.
in a database system. (b) With respect to the table PAYMENTS
Some DDL statements are as follows given below, write, output of the following
(i) CREATE used to create new table in the questions.
database.
(ii) DROP used to delete tables from the TABLE : PAYMENTS
database. Empld Emp_Name Salary Department
(iii) ALTER used to change the structure of the
1 Ridhi 20000 D1
database table. This statement can add up
additional column, drop existing, and even 2 Rohit 25000 D2
change the data type of columns involved in a 3 Rakesh 20000 D2
database table.
(iv) RENAME used to rename a table. 4 Roshan 44000 D1
or 5 Rohini 15000 D3
DML (Data Manipulation Language) provides 6 Radha 14000 D1
statements for manipulating the database objects.
It is used to query the databases for information (i) To display the average of employees salary
retrieval. Some DML statements are as follows from PAYMENTS table.
(i) INSERT used to insert data into a table. (ii) To count the total number of employees from
(ii) SELECT used to retrieve data from a PAYMENTS table Department wise
database. (iii) To count distinct values of column Department
(iii) UPDATE used to update existing data within from PAYMENTS table.
a table. (iv) To display department wise number of
(iv) DELETE used to delete all records from a employees , but for only those departments
table. where number of employees are more than 2.

Sol :
Section C (a) SELECT Last_Name, First_Name,
Order_No
26. (a) Consider the following tables PERSON and
ORDERS FROM PERSON, ORDERS
WHERE PERSON.P_Id = ORDERS.P_Id
Table : PERSON ORDER BY PERSON.Last_Name;
P_Id Last_Name First_Name City (b) (i) SELECT AVG(Salary) FROM
1 Sharma Abhay Mumbai PAYMENTS;
2 Gupta Mohan Delhi (ii) SELECT Department, COUNT(*)
FROM PAYMENTS GROUP BY
3 Verma Akhil Mumbai Department;
(iii) SELECT COUNT(DISTINCT
Table : ORDERS Department) FROM PAYMENTS;
O_Id Order_No P_Id (iv) SELECT Department, COUNT(*)
1 10050 3
FROM PAYMENTS GROUP BY
Department HAVING COUNT(*) >2;
2 25000 3
Page 5 Sample Paper 1 Computer Science Class 12

27. Write a code in Python to open a Binary file if(c>0):


“College.dat” containing records of students as print(“Total lines started with
per following structure: the word ‘OPEN’ is/are:”,c)
Roll Name SemPercentage else:
The code should display only records of students print(“There is no line started
from the file where the percentage is greater than with the word ‘OPEN’ ”)
30. f.close()
or else:
Write a method countopen( ) to count and print(“File does not exist”)
display the number of lines starting with the word
28. (a) Write SQL commands from (i) to (iv) on the
‘OPEN’ (including lower cases and upper cases)
basis of the table INTERIORS given below
present in a text file “start. txt”.
e.g. If the file “start.txt” contains the following TABLE : INTERIORS
lines: No ITEMNAME TYPE DATEOF- PRICE DISC-
Get the data value to be deleted, STOCK OUNT
Open the file for reading from it. 1 Red rose Double 23/02/02 32000 15
Read the complete file into a list Bed
Delete the data from the list 2 Soft touch Baby 20/01/02 9000 10
Open the file cot
Open same file for writing into it 3 Jerry’s home Baby 19/02/02 8500 10
Write the modified list into file. cot
Close the file. 4 Rough wood Office 01/01/02 20000 20
The method should display Table
Total lines started with word ‘OPEN’ is/are: 3 5 Comfort zone Double 12/01/02 15000 20
Bed
Sol :
6 Jerry look Baby 24/02/02 7000 19
stud=[] cot
f=open(“College.dat”,“rb”) 7 Lion king Office 20/02/02 16000 20
while True: Table
try: 8 Royal tiger Sofa 22/02/02 30000 25
stud=pickle.load(f)
9 Park sitting Sofa 13/12/01 9000 15
if stud[2]>30:
print(stud) 10 Dine Dining 19/02/02 11000 15
Paradise Table
except EOFError:
print(“End of file”) 11 White Wood Double 23/03/03 20000 20
Bed
break
f.close() 12 James 007 Sofa 20/02/03 15000 15

or 13 Tom look Baby 21/02/03 7000 10


cot
import os
def countopen(): (i) To show all information about the Sofa
if os.path.isfile(“start.txt”): from the INTERIORS table.
f=open(“start.txt”,“r”) (ii) To list the ITEMNAME, which are
c=0 priced at more than 10000 from the
print(“The lines are:”) INTERIORS table.
while True: (iii) To list ITEMNAME and TYPE of those
l=f.readline( ) items, in which DATEOFSTOCK is
l=l.rstrip( ) before 22/01/02 from the INTERIORS
print (l) table in descending order of ITEMNAME.
if not l:
(iv) To insert a new row in the INTERIORS
break
table with the following data
list1=l.upper().split()
if(list1[O]== ‘OPEN’): {14, ‘TrueIndian’, ‘Office
c=c+1 Table’, ‘25/03/03’, 15000, 20}
Page 6 Sample Paper 1 Computer Science Class 12

(b) Write the command to display the sum of display elements in a stack.
prices of items of type “cot”. Algorithm Steps to Display all the Elements of
the Stack
Sol :
1. Start
(a) (i) SELECT * FROM INTERIORS WHERE 2. if (Top == – 1)go to step 3
TYPE = ‘Sofa’; else go to step 4
(ii) SELECT ITEMNAME FROM INTERIORS 3. Print “Stack is empty” and go to
WHERE PRICE > 10000; step 7
(iii) SELECT ITEMNAME, TYPE FROM 4. Print the Top element of the stack
INTERIORS WHERE DATEOFSTOCK < 5. Decrement Top by 1
‘22/01/02’ ORDER BY ITEMNAME 6. if (Top == – 1) go to step 7
DESC; else go to step 4
(iv) INSERT INTO INTERIORS VALUES 7. Stop
(14, ‘TrueIndian’, ‘Office or
Table’, ‘25/03/03’, 15000,
Scanned Operation Stack
20);
Elements status
(b) SELECT SUM(PRICE) FROM INTERIORS
WHERE Type LIKE “%cot”; 7 Push 7
11 Push 7, 11
29. Write a user defined function to accept a string
and check whether it is palindrome or not. * Pop twice 7*11 = 77 77
(A palindrome is a string that is same as its 80 Push 77, 80
reverse)
+ Pop twice 77+80=157 157
Sol :
50 Push 157, 50
def checkPalin( ):
+ Pop twice 157 + 50 = 207 207
string = input (“Enter the string:”)
str1 = “” Output 207
for i in string:
str1 = i + str1
print (“string in reverse order:”, Section D
str1)
if (string == str1): 31. Tech Up Corporation (TUC) is a professional
print (“This is a palindrome consultancy company. The company is planning
string”) to set up their new offices in. India with its hub
else : at Hyderabad. As a network adviser, you have
print (“This is not a palindrome to understand their requirement and suggest to
string”) them the best available solutions. Their queries
are mentioned as (i) to (v) below.
30. Explain the traversal operation in a stack. Physical locations of the blocks of TUC
Write the algorithm for Traversal of a stack to
display its contents.
You need not to write the actual code.
or
Find the final contents of a stack that encounters
the following tokens.
Assume that an operand is pushed to stack and
a binary operator pops two operands from stack
and pushes the result to the stack.
7,11,*,80,+,50,+ Block to block distances (in metre)
Sol : Block (From) Block (To) Distance
Moving through the elements of the stack is known Human Resource Conference 60
as traversal. Traversing is the basic operation to
Page 7 Sample Paper 1 Computer Science Class 12

Human Resource Finance 120 (b) Write a code in Python to update the class of
a student to 12 whose roll number is 22. The
Conference Finance 80 table structure is as follows :
Expected number of computers to be installed RollNo Name Class Perc
in each block Note :
Database : PythonDB
Block Computers Table : Student
Human Resource 125 Host : localhost
UserId : root
Finance 25
Password : arihant
Conference 60 or
(i) What will the most appropriate block, where (a) Write the output of the following function
TUC should plan to install their server? def showOutput( ):
(ii) Draw a block to block cable layout to connect num=4 + float(7)/int(2.0)
all the buildings in the most appropriate print(“num =”, num)
manner for efficient communication. (b) Write a code in Python to delete the record
(iii) Write names of different types of Modems. of a student whose rollno is 33. The table
(iv) Which of the following devices will be structure is as follows
suggested by you to connect each computer RollNo Name Class Perc
in each of the buildings? Note :
(a) Gateway (b) Switch (c) Modem Database : PythonDB
(v) Company is planning to connect its Block in Table : Student
Hyderabad which is more than 20 km. Which Host : localhost
type of network will be formed? UserId : root
Password : arihant
Sol :
Sol :
(i) TUC should install its server in Human
Resource Block as it has maximum number (a) Corrected code
of computers. s=“WelcometoCS”
(ii) for a in s :
if a in “aeiou” :
print(a)
else :
print(“False”)
(b) import mysql.connector
con = mysql.connector.connect
(host = “localhost”, user = “root”,
passwd = “arihant”,
The above layout is based on the minimum
database = “PythonDB”)
length of cable required, i.e. 140 m.
cursor = con.cursor()
(iii) Internal Modem : Fixed inside the computer.
try :
External Modem : Attached externally to a
cursor.execute (“update Student
computer
set Class = 12 where RollNo 22”)
(iv) (b) Switch
con.commit()
(v) MAN
except :
32. (a) Underline the errors in the following code and con.rollback()
write the correct code: con.close()
s= “WelcometoCS” or
For a IN s : (a) num = 7.5
If a IN “aeiou” : (b) import mysql.connector
print(a) con = mysql.connector.connect
else (host = “localhost”, user = “root”,
print(“False”) passwd = “arihant”,
Page 8 Sample Paper 1 Computer Science Class 12

database = “PythonDB”) hotellst=[roomid,cname,days]


cursor = con.cursor() pickle.dump(hotellst,f)
try: ans=input(“Continue(y/n)”)
cursor.execute (“delete from f.close()
Student where RollNo = 33”) def ShowReservations():
con.commit() f=open(“Hotel.dat”,“rb”)
except: while True:
con.rollback() try:
con.close() 1st=pickle.load(f)
print(“Room ID :”,1st[0])
33. What is the use of writerows() function for CSV print(“Customer Name :”,
files? 1st[1])
A binary file “Hotel.dat” exists storing details of print(“Days :”, 1st[2])
hotel customers as per following structure: except EOFError:
Roomld CustomerName Days print(“No more records”).
Write a program in python for adding and break
displaying records from the binary file using f.close()
following functions Reserve()
(a) Reserve() : To add data of customers to the ShowReservations()
binary file. or
(b) ShowReservations() : To open the file “Hotel. The csv.reader () function returns a reader object
dat” and display all the records. that helps in reading rows as per the delimiter
or specified.
What is csv. reader() function? This reader object is used to iterate over lines in
A binary file “Telephone.dat” exists storing details the given csvfile.
of BSNL customers as per following structure: Program:
PhoneNo CustomerName ConnType import. pickle
Write a program in python for adding and def NewCustomer():
displaying record count from the binary file using f=open(“Telephone.dat”,“ab”)
following functions ans=‘y’
(a) NewCustomer() : To add data of customers to pno =””
the binary file “Telephone.dat”. cname=””
Note : The existing connection data should be ctype=””
preserved. while ans==‘y’:
(b) PrintConnections() : To open the file pno=input(“Enter telephone
“Telephone.dat” and display the connections number .”)
and number of connections. cname=input(“Enter customer
Sol : name ”)
ctype=input(“Enter connection
writerows(rows) function writes multiple rows
Type”)
(sequence) to the writer’s file object.
phone1st=[pno,cname,ctype]
Program:
pickle.dump(phonelst,f)
import pickle
ans=input(“Continue(y/n)”)
def Reserve():
f.close()
f=open(“Hotel.dat”,“wb”)
def PrintConnections():
ans=‘y’
f=open(“Telephone.dat”, “rb”)
roomid=“”
while True:
cname=“”
try:
days=“”
phonelst=pickle.load(f)
while ans==‘y’:
print(“Phone No. :”,
roomid=input(“Enter room id”)
phone1st[0])
cname=input(“Enter customer
print(“Customer Name :”,
name ”)
phone1st[1])
days=input(“Enter days”)
Page 9 Sample Paper 1 Computer Science Class 12

print((Connection Type :”, Primary key(No);


phone1st[2])
except EOFError 35. A program in python to modify records of a
print(“End of file”) binary file “hotel.dat” using random access. The
break program would accept the room id , search the
f.close() record by random access and display. It will then
NewCustomer() accept the new data and modify the file.
PrintConnections() The file structure is :
Roomld Customer Name Days
import pickle
Section E 1st=[]
f=open(“hotel.dat”, “rb+”)
34. Consider the following table ans=‘y’
while ans==‘y’:
TABLE : INTERIORS r=int(input(“Enter roomid to
No ITEMNAME TYPE DATEOF- PRICE DIS- modify :”))
STOCK CO- 1st=pickle.load(f)
UNT
size=f.tell()
1 Red rose Double 23/02/02 32000 15 f.seek(0)
Bed
f.seek((r-1)*size)
2 Soft touch Baby cot 20/01/02 9000 10 1st=pickle.load(f)
3 Jerry’s home Baby cot 19/02/02 8500 10 print(“old record ”)
(i) What should be the data type for the print(“Room Id :”, 1st[0])
DATEOFSTOCK column? print(“Customer :”, 1st[1])
(ii) Write a command to add a new record as print(“Days :”, 1st[2])
follows : f.seek(0)
4, “Morris”,”Sofa Set” ... ... ... # Statement 1
Rest of the field values are not given print(“Enter new record ”)
(iii) Write statements to : nm=input(“Enter, customer name
(a) Write a command to display only :”)
the Column ITEMNAME, Net days=input(“Enter days :”)
Amount(PRICE-DISCOUNT) rs=str(r)
(b) Display only ITEMNAME and Discount 1st=[rs,nm,days]
column. pickle.dump(1st,f)
(Option for part (iii) only) ans=input(“Modify another(y/n)”)
(a) Which clause is to be used to search non f.close()
blank values in the table? (i) What type of data is returned by the load()
(b) Which command will be used to make method?
the “No” column as the primary key? (ii) Which method closes a binary file?
(iii) What will be inserted in statement 1?
Sol :
Sol :
(i) Date
(ii) INSERT INTO INTERIORS(No, ITEMNAME, (i) Sequence
TYPE) VALUES(4, “Morris”, “Sofa (ii) close()
Set”); (iii) f.seek((r–1)*size)
(iii) (a) SELECT ITEMNAME, PRICE-
DISCOUNT AS “Net Amount” FROM
INTERIORS;
END
(b) SELECT ITEMNAME, DISCOUNT FROM
INTERIORS;
or
(a) NOT NULL
(b) ALTER TABLE INTERIORS ADD
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 8 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. The join operation can join..........tables.


Section A (a) 1 (b) 2
(c) 3 (d) Multiple
1. What is the output of the following code?
Sol :
>>> a = 10
>>> b = 2 (d) Multiple
>>> print(“Output is”,(a+10*2+b))
(a) Output is 22 (b) Output is 32 6. A table can have maximum..........primary key(s).
(c) Output is None (d) None of these (a) 1 (b) 2
(c) 3 (d) Many
Sol :
Sol :
(b) Output is 32
(a) 1
2. The...............mode opens a file for both reading
and writing. 7. State True or False
(a) wr (b) rw “A tuple is an Editable data store”.
(c) r+ (d) a+ Sol :
Sol : False
(c) r+ 8. Which comments start with # symbol?
3. Give the output for the following program segment (a) Double line (b) Multi-line
given below. (c) Single line (d) All of these
for i in range (-5,-7,-1): Sol :
print (i + 1) (c) Single line
(a) -7,-6,-5 (b) -5,-6,-7
(c) No output (d) Error 9. A table needs to restrict Salary column values to
Sol : more than 50000. The constraint that has to be
used is
(c) No output (a) NULL
4. For readline(), a line is terminated by (b) PRIMARY KEY
(a) ‘\n’ (b) EOF (c) CHECK
(c) Either (a) or (b) (d) None of these (d) NOT NULL

Sol : Sol :

(c) Either (a) or (b) (c) CHECK


Page 2 Sample Paper 1 Computer Science Class 12

10. To insert a record from Python to a mysql (a) BETWEEN


database the...........function needs to be executed. (b) ORDER BY
(a) execute() (c) HAVING
(b) executeUpdate() (d) GROUP BY
(c) executeQuery()
Sol :
(d) None of these
(d) GROUP BY
Sol :
(a) execute() Directions (Q. Nos. 17-18) are Assertion and
Reason based questions.
11. You can repeat the elements of the tuple using
which operator? 17. Assertion (A) Default parameters to a function
(a) * (b) + are not compulsory but are a good practice to
(c) ** (d) % specify.
Reason (R) If default parameters are specified the
Sol : formal parameters will take the default values , if
(a) * any of the actual parameters are not passed.
(a) Both A and R are true and R is the correct
12. A table can be sorted by...........fields. explanation for A.
(a) 1 (b) 2 (b) Both A and R are true and R is not the
(c) More than 2 (d) None of these correct explanation for A.
Sol : (c) A is true but R is false.
(d) A is false but R is true.
(c) More than 2
Sol :
13. A device that connects the network cable to the
(a) Both A and R are true and R is the correct
NIC is
explanation for A.
(a) RJ45 (b) Repeater
(c) Hub (d) Switch 18. Assertion (A) A recursive function requires a base
Sol : condition.
Reason (R) The base condition is the one that
(a) RJ45
makes the function exit at a point.
14. Which index number is used to represent last (a) Both A and R are true and R is the correct
character of string? explanation for A.
(a) – 1 (b) 1 (b) Both A and R are true and R is not the
(c) 0 (d) n – 1 correct explanation for A.
(c) A is true but R is false.
Sol : (d) A is false but R is true.
(a) –1 Sol :
15. What will be the output of the following code? (a) Both A and R are true and R is the correct
a, b = 10, 5 explanation for A.
x, y = a + b, b – 2
z = x – y
print (“x:”, x, “y:”, y, “z:”, z) Section B
(a) x: 16 y:3 z:20
(b) x: 15 y:3 z:20 19. Predict the output.
(c) x: 16 y:3 z:12 (i) ‘wonders’.center(12, ‘*’)
(d) x: 15 y:3 z:12 (ii) ‘wonders25’.isalnum( )
Sol :
Sol :
(d) x: 15 y:3 z:12
(i) ‘**wonders***’
16. The...........clause groups records by common (ii) True
values of a column.
Page 3 Sample Paper 1 Computer Science Class 12

20. Identify the types of networks formed in the (ii) High speed SQL queries can be used to
following cases : retrieve large amount of records from a
(a) Two friends sharing files between a distance database quickly and efficiently.
of 1000 km. (iii) Easy to learn and understand SQL generally
(b) A device transmitting voice to stations within consists of english language statements and it
a distance of 30 km. is very easy to learn and understand.
or (iv) SQL is used for relational database SQL is
Write names of protocols used in following cases : widely used for relational database.
(a) A network user downloading a photograph
from a server 23. (a) Identify whether the following address is a
(b) Two friends chatting over the web. valid IP address or not 256.200.192.1
(b) What is the difference between domain name
Sol : and IP address?
(a) WAN - Wide Area Network Sol :
(b) MAN - Metropolitan Area Network
or (a) It is not an IP address as the numbers in the
(a) FTP - File Transfer Protocol IP addresses can be within 0-255.
(b) IRCP - Internet Relay Chat Protocol (b) IP address is an identifier for a computer or
device on a TCP/IP network.
21. (a) Given the following code : e.g. 1.160.10.240 could be an IP address.
str1 = input (“Enter the string:”) A domain name is a name that identifies one
final = “” or more IP addresses.
for i in range(len(str1)): e.g. The domain name microsoft.com
if (i%2 == 0): represents about a dozen IP addresses.
final = final + str1[i]
print(“Modified string is : ”, 24. Distinguish between tuple and list.
final) or
What is the above code doing? How can you add following data in empty
(b) Consider the following list and answer the dictionary?
below questions. Keys Values
l = [6, 9, 8, ‘Hi’, ‘Hello’, 45,
23, ‘New’] A One
(i) l[4:] B Two
(ii) l[-4]
C Three
(iii) l[2:5]
(iv) ‘World’ in l D Four

Sol : Sol :
(a) The code removes the characters-at the odd Differences between tuple and list are as follows
indices of a string. The loop iterates through Tuple List
the length of the string and Checks the
Elements of a tuple are Elements of a list are
even positions. Extracts characters at these
immutable. mutable.
positions and creates a new string.
(b) (i) [‘Hello’, 45, 23, ‘New’] Tuple is declared in List is declared in
(ii) Hello parenthesis (). square brackets [ ].
(iii) [8, ‘Hi’, ‘Hello’] Tuples cannot be Lists can be changed
(iv) False changed after creation. after creation.
22. Write few advantages of SQL. Iterating over the Iterating over the
elements of a tuple is elements of a list is
Sol :
fast. slow.
(i) SQL is portable It is not platform dependent, or
it can be used in all types of devices; PCs, dic = { }
laptops and even mobile phones also. dic[‘A’] = ‘One’
Page 4 Sample Paper 1 Computer Science Class 12

dic[‘B’] = ‘Two’
dic[‘C’] = ‘Three’
Section C
dic[‘D’] = ‘Four’
26. (a) Consider the tables EMP and SALGRADE
25. What is equi join ? Explain with an example. storing details of employees and their salaries.
or
Table: EMP
Identify which of the functions given below are
aggregate functions. empno ename sal date
COUNT() , LEFT() , RIGHT() , MAX() , AVG() 110 Priya 7000 11-11-2010
, TRIM()
111 Seema 14000 15-02-2014
Sol :
151 Sachin 30000 18-04-2015
Equi join is a simple SQL join condition that uses
142 Deepa 25000 20-05-2015
equal sign as a comparison operator.
Syntax
SELECT col1, col2, col3 Table : SALGRADE
FROM table1, table2 empno city lowsal hisal grade
WHERE table1.col1 = table2.col1;
e.g. Consider the following tables PERSON and 110 Delhi 5000 10000 2
ORDERS 111 NCR 11000 13000 1

TABLE : PERSON 142 Meerut 10000 20000 5

P_Id Last_Name First_Name City With respect to the tables given above write a
command to display the Employee names and the
1 Sharma Abhay Mumbai corresponding cities.
2 Gupta Mohan Delh (b) With respect to the tables given above , write
commands for the following :
3 Verma Akhil Mumbai
(i) To display the average salaries of all
employees who are not from Delhi.
TABLE : ORDERS (ii) To display, maximum salary from the
O_Id Order_No P_Id EMP table among employees whose date
is after “2014”
1 10050 3
(iii) To find the count of employees who are
2 25000 3 from “Delhi”
3 5687 1 (iv) To display each employee’s name and
Grade.
4 45000 1
Sol :
5 35000 15
(a) SELECT EMP.ename, SALGRADE.city
To display the order numbers and corresponding
first names the command using equi join concept
FROM EMP, SALGRADE WHERE EMP.
is :
empno = SALGRADE.empno;
(b) (i) SELECT AVG(sal) FROM EMP t1,
SELECT ORDERS.Order_No, PERSON.
SALGRADE t2 WHERE t1.empno=t2.
First_Name FROM, ORDERS, PERSON WHERE
Empno AND NOT t2.city =“Delhi”;
ORDERS.P_Id = PERSON.P_Id;
(ii) SELECT MAX(sal) FROM EMP WHERE
or
Aggregate functions are those that work on a
date> “2014-12-31”;
(iii) SELECT COUNT(*) FROM EMP t1,
group of records to generate aggregate results.
Among the above, the aggregate functions are :
SALGRADE t2 WHERE t1.empno=t2.
COUNT() - This function counts the number of empno AND t2.city =“Delhi”;
(iv) SELECT ename, grade FROM EMP t1 ,
rows.
MAX() - Returns the maximum among the values
SALGRADE t2 WHERE t1.empno=t2.
in a column.
empno AND (sal BETWEEN lowsal
AVG() - Returns the average of the values in a
AND hisal);
field or column.
Page 5 Sample Paper 1 Computer Science Class 12

27. Write a method Filterwords() to find and display F0001 3


words from a text file ‘NewsLetter.txt’
whose length is less than 4. T0001 1
or C0001 5
Write a method countAN() that checks the (i) To show Book name, Author name and
number of occurrance of “A” and “N” in a text Price of books of EPB Publishers.
file “Story.txt”. (ii) To list the names from books of Fiction
Sol : type.
(iii) To display the names and price of the
def Filterwords(): books in descending order of their price.
c=0 (iv) To increase the price of all books of First
file=open(‘NewsLetter.txt’, ‘r’) Publ Publishers by 50.
line=file.read() (b) Write the command to remove all the records
word=line.split(‘ ’) of the BOOKS table keeping the structure.
for c in word:
if len(c)<4: Sol :
print(c) (a) (i) SELECT Book_Name, Author_
file.close() Name, Price FROM BOOKS WHERE
or Publishers = ‘EPB’;
def countAN(): (ii) SELECT Book_Name FROM BOOKS
countA=O WHERE Type = ‘Fiction’;
countN=O (iii) SELECT Book_Name, Price FROM
file=open(“Story.txt”, “r”) BOOKS ORDER BY Price DESC;
data=file.read() (iv) UPDATE BOOKS SET Price = Price
for ch in data : + 50
if ch in “A” : WHERE Publishers = ‘First
countA+=1 Publ’;
elif ch in “N” (b) DELETE FROM BOOKS;
countN+=1
print(“Number of A :”, countA) 29. Write user defined function patterns (n) to
print(“Number of N :”, countN) display the following pattern for n lines , as per
file.close() the number passed to the function. The number
to be input in main() function.
28. (a) Given the following tables for a database Example :
LIBRARY Enter a number : 6
Write SQL commands (i) to (iv) with respect 6
to the tables BOOKS and ISSUED 66
TABLE: BOOKS
66 6
66 66
Book_ Book Author_ Publishers Price Type Qty
Id Name Name 66 666
F0001 The Tears William First Publ 750 Fiction 10
66 6666
Hopkins Enter a number :7
F0002 Thunder Anna First Publ 700 Fiction 5 7
bolts Roberts 77
T0001 My First Brain & EPB 250 Text 10 777
C++ Brooke
7777
T0002 C++ A.W. TDH 325 Text 5 77777
Brainworks Rossaine
777777
C0001 Fast Cook Lata EPB 350 Cookery 8
Kapoor 7777777
Sol :
TABLE : ISSUED
def patterns(n):
Book_Id Quantity_Issued for i in range(1,n+1):
for j in range(1,(i+1)):
Page 6 Sample Paper 1 Computer Science Class 12

print(n,end=‘ ’)
print()
Section D
def main():
n=int(input(“Enter a number :”)) 31. G.R.K International Inc. is planning to connect
patterns(n) its Bengaluru Office Setup with its Head Office in
main() Delhi. The Bengaluru Office G.R.K. International
Inc. is spread across an area of approx. 1 square
30. A linear stack called status contains the following kilometres consisting of 3 blocks. Human
information : Resources, Academics and Administration. You
Phone number of Employee as a network expert have to suggest answers to
Name of Employee the questions (i) to (v) raised by them.
Write the following methods to perform given Note Keep the distances between blocks and
operations on the stack status : number of computers in each block in mind, while
(i) Push_element ( ) To Push an object providing them the solutions.
containing Phone number of Employee and
Name of Employee into the stack.
(ii) Pop_element ( ) To Pop an object from the
stack and to release the memory.
or
Write a function to pop an element from a stack
“s” using a function stackpop().
Sol :
def Push_element (Status, Top): Shortest distances between various blocks
phone_no = int (input (“Enter
phone number :”)) Human Resources to Administration 100 m
emp_name = input (“Enter employee Human Resources to Academics 65 m
name :”)
St = (phone_no, emp_name) Academics to Administration 110 m
Status.append (St) Delhi Head Office to Bengaluru 2350 km
Top =Top + 1 Office Setup
Number of computers installed at various blocks
return Top
def Pop_element (Status, Top) :
Slen = len (Status) Block Number of Computers
if (Slen <= 0) : Human Resources 155
print (“Status is empty”)
Administration 20
else :
phone_no, emp_name = Status.Pop() Academics 100
Top = Top – 1 Delhi Head Office 20
print(“Phone number %s and name (i) Suggest the most suitable block in the
%s Bengaluru Office Setup to host the server.
deleted” % (phoneLno, emp_name)) Give a suitable reason with your suggestion.
(ii) Suggest the cable layout among the various
return Top
or
blocks within the Bengaluru Office Setup for
def stackpop(s): connecting the blocks.
if Empty(s):
(iii) Suggest the placement of switch.
return “Underflow”
else : (iv) Suggest the most suitable media to provide
x=s.pop() secure, fast and reliable data connectivity
if len(s)==0: between Delhi Head Office and the Bengaluru
Top=None Office Setup.
else : (v) Expand the following
Top=len(s)–1 WAN
return x LAN
Page 7 Sample Paper 1 Computer Science Class 12

Sol : print (‘,’.join(1))


(i) Human Resources, because it has maximum (b) import mysql.connector
number of computers. mycon = mysql.connector.connect
(ii) (host = “localhost”,
user = “root”, passwd = “system”,
database = “Test”)
cursor = con.cursor ( )
sql = “INSERT INTO Faculty (F_ID,
Fname, Lname, Hire_date,
Salary, Course_Name) VALUES
(%s, %s, %s, %s, %s, %s)”
val = [(101, ‘Riya’, ‘Sharma’,
‘12-10-2004’, 35000,
(iii) Switches are needed in every building as they ‘Java Advance’), (102,
share bandwidth in every building. ‘Kiyaan’, ‘Mishra’,
(iv) Satellite ‘3-12-2010’, 28000,
(v) Wide Area Network ‘Data Structure’)]
Local Area Network try:
cursor.executemany (sql, val)
32. (a) Write a program which will find all such
mycon.commit ( )
numbers which are divisible by 7 but are not
except :
a multiple of 5, between 200 and 300 (both
mycon.rollback ( )
included).
mycon.close ( )
(b) Consider the table Faculty whose columns’
or
name are
(a) (i) Valid
F_ID, Fname, Lname, Hire_date,
(ii) Invalid, -is not allowed in the variable
Salary, Course_name
name.
Write the code to insert the following record
(iii) Valid
into the above table.
(iv) Invalid, first character must be alphabet.
101 Riya Sharma 12-10-2004 35000 Java (b) fetchall() method fetches all the rows of a
Advance query result. It returns all the rows as a list
102 Kiyaan Mishra 3-12-2010 28000 Data of tuples. An empty list is returned if there is
Structure no record to fetch.
or e.g. To fetch all records from database
(a) Which of the following are invalid, names and PythonDB
why? import mysql.connector
(i) PaidInterest (ii) S-num con = mysql.connector.connect
(iii) Percent (iv) 123 (host = “localhost”, user = “root”,
(b) What is the utility of fetchall() method? passwd = “arihant”,
Write a code to fetch all the records of a database = “PythonDB”)
Student table from PythonDB Database. cursor = con.cursor ( )
Note : try :
Host : localhost cursor.execute (“select *from
Database : PythonDB Student”)
User : root display = cursor.fetchall( )
Password:arihant for i in display :
Table : Student print(i)
except :
Sol :
con.rollback( )
(a) l = [] con.close( )
for i in range(200, 300):
if (i%7 == 0) and (i%5! = 0):
l.append(str(i))
Page 8 Sample Paper 1 Computer Science Class 12

33. Which file can be opened with notepad as well as else:


MS Excel? print(“Invalid garment
A CSV file “Garment.csv” file exists containing type!!!”)
records of different types of garments as per ans=input(“Continue(y/n)”)
following structure. f.close()
GarmentlD Type Gender Cost def ShowGarments():
Write a python program to add and search records count=0
of garments from the csv file and display using f=open(“Garment.csv”,“rb”)
the following functions : while True:
(a) AddGarment() : Function to input details of try:
garments and store them to the file “Garment. glst=pickle.load(f)
csv”, if the garment type is “cotton” or “silk”. if glst[1]==“silk”:
(b) ShowGarments() : To open the file “ Garment. count+=1
csv”, display details and number of “silk”. print(“Garment ID.:”, , glst[0])
garments print(“Garment Type :”, glst[1])
or print(“Gender :”, glst[2])
What is with statement in Python? print(“Price :”, glst[3])
A csv file “cricket.csv” exists to store data of print(“No. of silk garments ”:,
cricketers as follows: count)
CID CricketerName Strikerate WorldRank except EOFError:
Write a program in python to add data of more print(“End of file”)
cricketers along with the existing records . break
Also display the details of cricketers as per the f.close()
condition given using the functions given: AddGarment(
(a) AppendCricketer() : To accept data of ShowGarments()
cricketers and append them to the file or
“cricket.csv” with statement in Python is used in to simplify
(b) GetCricketers() : To open the file “Cricket. the management of common resources like file
csv” and display number of cricketers whose streams.
world ranking is above 50. It makes the code cleaner and much more readable.
Program :
Sol : import pickle
CSV file def AppendCricketer():
Program : f=open(“cricket.csv”,“ab”)
import pickle ans=‘y’
def AddGarment( ): cid=“”
f=open(“Garment.csv ”, “wb”) cname=“”
ans=‘y’ srate=0.0
gid=“” wrank=0.0
gtype=“” while ans==‘y’:
gen=“” cid=input(“Enter cricketer id.”)
gcost=0.0 cname=input(“Enter cricketer
while ans==‘y’: name ”)
gid=input(“Enter garment id.”) srate=float(input(“Enter Strike
gtype=input(“Enter Garment rate : ”))
type ”) wrank=float(input(“Enter world
gen=input(“Gender ”) rank ”))
gcost=float(input(“Enter cost clst=[cid, cname, srate, wrank]
”)) pickle.dump(glst,f)
glst=[gid, gtype, gen, gcost] ans=input(“Continue(y/n)”)
if gtype==”cotton” or gtype== f.close( )
“silk”: def GetCricketers( ):
pickle.dump(glst, f) count=0
Page 9 Sample Paper 1 Computer Science Class 12

f=open(“Cricket.csv”,“rb”) 35. A user defined method to open a text file “para.


while True: txt” and display count of number of ‘c’ or ‘C’ and
try: number of ‘e’ or ‘E’ separately.
clst=pickle.load(f) def test():
if int(clst[3])>50: f=open(“Para.TXT”)
count+=1 n1=0
print(“Number of cricketers above n2=0
world rank 50 : ”, count) while True:
except EOFError: 1=........... //Statement
break if not 1:
f.closen() break
AppendCricketer() for i in 1:
GetCricketers() if (i ==‘E’ or i ==‘e’):
n1=n1+1
elif(i==‘C’ or i==‘c’):
Section E n2=n2+1
print(n1)
34. Consider the following table print(n2)
f.close()
TABLE : PATIENTS
(a) Which module needs to be imported to use
No Name Age Department Dateofadm Charges Sex text file handling functions?
1 Ketaki 16 ENT 24/02/98 300 F (b) Write the functionname to close a file object.
2 Ankita 29 Cardiology 20/02/98 800 F (c) Write the code best suitable for statement as
marked.
3 Zareen 45 Gynaecology 22/02/98 300 F
4 Kush 19 Cardiology 13/01/98 800 M Sol :
5 Shailya 31 Nuclear 19/02/98 400 M (a) Text file handling functions do not require
Medicine any module to be imported.
(i) What would be the width of Dateofadm field? (b) close() function closes a file object.
(ii) Write commands to remove the records of (c) f.readline( )
“Cardiology” department.
(iii) Write statements to :
(a) Display a report showing Name, charges
END
and discount (15%) for all patients.
(b) Display names of female patients .
or (option for part (iii) only)
(a) Which function will find the total charges
of all patients?
(b) Name the constraint that will restrict
duplicate values in Name column.
Sol :
(i) 8 – Date field has fixed width 8
(ii) DELETE FROM PATIENTS WHERE
Department=“Cardiology”;
(iii) (a) SELECT Name, Charges, Charges*0
.15 AS “Discount” FROM PATIENTS;
(b) SELECT Name FROM PATIENTS WHERE
Sex=“F”;
or
(a) SUM()
(b) Unique
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 9 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. State True or False


Section A “A tuple is a immutable data type.”
Sol :
1. The alternate to math.pow() function is______
operator. True
(a) ** (b) c $
(c) + = (d) / 6. Which of the following Python functions do not
require importing of a module?
Sol : (a) type() (b) input()
(a) ** (c) sqrt() (d) Both (a) and (b)
Sol :
2. Two relations are joined using a common field
called______ (d) Both (a) and (b)
(a) Alternate key (b) Foreign key
(c) Candidate key (d) None of these 7. Which of the following modes open a text file,
such that the new data is written in it keeping the
Sol : existing contents ?
(b) Foreign key (a) r+ (b) rw+
(c) w+ (d) a
3. To print all elements of tuple in reverse order
Sol :
using______.
(a) [: – 1] (b) [: : – 1] (d) a
(c) [1 : : ] (d) [: : 1]
8. The_____clause with the update command
Sol : specifies the attribute to be modified.
(b) [: : – 1] (a) FIELD (b) ATTRIBUTE
(c) CHANGE (d) SET
4. Given : s=“Olympic@gmail.com”. What will be
Sol :
the output of print(s[2: :2])?
(a) ‘ypcalcm’ (d) SET
(b) ‘ypcgalcm’
(c) ‘ypcglcm’ 9. Which of the following refers to a small, single
(d) ‘pcgalm’ site network?
(a) DSL (b) RAM
Sol : (c) WAN (d) PAN
(b) ‘ypcgalcm’ Sol :
Page 2 Sample Paper 1 Computer Science Class 12

(d) PAN 16. Which attribute is used to return access mode


with that file was opened?
10. Write the output of given code: (a) file.mode
s1 = ‘Hello’ (b) mode.file
s2 = ‘World’ (c) file*mode
s = s1 + s2 (d) None of these
print(s)
(a) Hello World (b) HelloWorld Sol :
(c) ‘Hellow’ ‘World’ (d) Error (a) file.mode
Sol : Directions : (Q. Nos. 17 and 18) are Assertion
(b) HelloWorld and Reason based questions.

11. The_____clause with GROUP BY, can filter 17. Assertion (A) A python function can return more
groups from the query output. than one value to the calling function.
(a) WHERE (b) FILTER Reason (R) The return statement takes only a list
(c) HAVING (d) CHECK as parameter.
(a) Both A and R are true and R is the correct
Sol :
explanation of A.
(c) HAVING (b) Both A and R are true but R is not the
correct explanation of A.
12. Given a list L= [6,12,9,40,2,1]. Which of the
(c) A is true but R is false.
following statements will arrange the list in
(d) A is false but R is true.
reverse order
(a) L.arrange() Sol :
(b) L.sort() (b) Both A and R are true but R is not the correct
(c) L.sort(reverse=True) explanation of A.
(d) L.sort(reverse=False)
18. Assertion (A) While opening a binary file the
Sol :
mode may not be specified.
(c) L.sort(reverse=True) Reason (R) The open function for file opening
by default takes the mode parameter as ‘rb’ for
13. Which method returns the next row from the
binary files, if no mode is specified.
result set as tuple?
(a) Both A and R are true and R is the correct
(a) fetchone( ) (b) fetchmany( )
explanation of A.
(c) fetchall( ) (d) rowcount
(b) Both A and R are true but R is not the
Sol : correct explanation of A.
(a) fetchone() (c) A is true but R is false.
(d) A is false but R is true.
14. An alternate key can be
Sol :
(a) only 1 in a table.
(b) a table can have maximum 2 alternate keys. (a) Both A and R are true and R is the correct
(c) a table can have at most 3 alternate keys. explanation of A.
(d) multiple in a relation.
Sol :
Section B
(d) Multiple in a relation
19. Find the output of the following code :
15. Which statement of SQL provides statements for
manipulating the database objects?
i=1
(a) DDL (b) DML
while(i<5):
(c) DCL (d) TCL
print(i)
i = i*2
Sol :
Sol :
(b) DML (Data Manipulation Language)
Page 3 Sample Paper 1 Computer Science Class 12

Output 22. Define UPDATE command of SQL with its basic


1 syntax and also give one of its example.
2
Sol :
4
The loop prints the values of i and squares the An UPDATE command is used to directly change
value of i. when i is 2, squaring it makes i=4, or modify the value stored in one or more fields in
hence the loop terminates. a specified record.
Syntax
20. Give one suitable example of each URL and UPDATE table name
domain name. SET column1 = value1,
or column2 = value2, ....
Can we use URL to access a web page? How? WHERE <condition>;
Sol : e.g. Consider the table PERSONS to update the
address as Nissestien 67.
URL-http : //www.gabsclasses.com/aboutus. UPDATE PERSONS SET Address =
Domain name-www.gabsclasses.com ‘Nissestien 67’;
or
Yes, as a location on a web server, which is called 23. (a) Write any two characteristics of IP address.
a website and each website has a unique address (b) What is VoIP?
known as URL. So, URL can be used to access a
Sol :
web page.
(a) (i) It is of 4 bytes.
21. (a) Correct the error if any in the following (ii) It is temporarily assigned.
statement. (b) VoIP (Voice over. Internet Protocol) is simply
(i) a + 5 = b the transmission of voice traffic over IP based
(ii) 1 = 2b + c * d networks. VolP has been around in one form
(iii) name = Aryan or another, since 1973 when it began as an
(iv) a = 20 experiment by US.
print a;
(b) Evaluate the following expression 24. Write the one example of following terms.
If a = b = 10, c = 5 (i) Identifier (ii) Punctuator
a = b*3//4 + c//4 + 4– b + 5//6 (iii) Keyword (iv) Constant
or
Sol : What will be the output of the following code?
(a) (i) b = a + 5 a, b = 10, 5
(ii) l= 2*b+c*d x, y = a + b, b – 2
(iii) name = “Aryan” z = x – y
(iv) a = 20 print (“x:”, x, “y:”, y, “z:”, z)
print (a)
Sol :
(b) a = 10*3//4 + 5//4 + 4 – 10 + 5//6
(i) Identifier " Sum_1
= 30//4 + 5//4 + 4 – 10 + 5//6 (ii) Punctuator " Bracket ( )
= 7 + 5//4 + 4 – 10 + 5//6 (iii) Keyword " for
(iv) Constant " ‘Neha’
= 7 + 1 + 4 – 10 + 5//6
or
= 7 + 1 + 4 – 10 + 0 Output
= 8 + 4 – 10 + 0 x : 15 y:3 z : 12

= 12 – 10 + 0 25. Expand the following abbreviation :


=2+0 (i) SQL (ii) DML
(iii) DDL (iv) TCL
a= 2 or
Mention two characteristics of SQL.
Sol :
Page 4 Sample Paper 1 Computer Science Class 12

(i) SQL-Structured Query Language (a) SELECT ClientName, City,


(ii) DDL-Data Definition Language ProductName , Price FROM CLIENT,
(iii) DML-Data Manipulation Language PRODUCT WHERE CLIENT.P_ID =
(iv) TCL-Transaction Control Language PRODUCT.P_ID;
or (b) (i) SELECT * FROM CLIENT WHERE
(i) SQL is a very simple and easy to learn. City=‘Delhi’;
(ii) SQL allows the users to create, update, delete (ii) SELECT * FROM PRODUCT WHERE
and retrieve data from a database. Price BETWEEN 50 AND 100;
(iii) SELECT ProductName,
Manufacturer FROM PRODUCT
Section C WHERE Price > 100;
(iv) SELECT ClientName FROM CLIENT
26. Consider the following tables PRODUCT and WHERE P_ID = “FW12”;
CLIENT 27. Define a function in Python to accept a sentence
TABLE : PRODUCT and count the number of occurrences of the word
“is” and “was”.
PID ProductName Manufacturer Price Example
TP01 Talcom Powder LAK 40 Input : “He is a good boy. She was and is a good
FW05 Face Wash ABC 45 girl”
Output :
BS01 Bath Soap ABC 55 No. of is : 2
SH06 Shampoo XYZ 120 No. of was : 1
or
FW12 Face Wash XYZ 95
Write a definition of a function that takes input
a sentence and display the list of words that start
TABLE : CLIENT with a lowercase vowel and list of words that start
C_ID ClientName City P_ID with a uppercase vowel separately.
Example
01 Cosmetic Shop Delhi FW05
Input : A quick black elephant enters Into a
06 Total Health Mumbai BS01 jungle.
12 Live Life Delhi SH06 Output
List of words starting with lowercase vowels
15 Pretty Woman Delhi FW12
[‘elephant’, ‘enters’, ‘a’]
16 Dreams Bengaluru TP01 List of words starting with uppercase vowels [‘A’,
(a) To display the ClientName, City from table ‘Into’]
CLIENT and ProductName and Price from Sol :
table PRODUCT, with their corresponding
matching P_ID. def counts(s):
iscount=0
(b) Write SQL queries for statements (i) to (iv)
wascount=0
(i) To display the details of those Clients, for w in s.split(‘ ’):
whose City is Delhi. if w==“is”:
(ii) To display the details of products, whose iscount+=1
Price is in the range of 50 to 100 (both elif w==“was”:
values included). wascount+=1
(iii) To display product name and their print(“No. of is :”, iscount)
manufacturer whose Price is more than print(“No. of was :”,wascount)
100. def main():
(iv) To display client name for those whose counts (“He is a good boy. She was
product id is FW12. and is a good girl”)
main()
Sol : or
def counts(s):
Page 5 Sample Paper 1 Computer Science Class 12

L1=[] Sol :
L2=[] (a) (i) SELECT NAME FROM STUDENT WHERE
for w in s.split(‘ ’): STREAM =‘COMPUTER’;
if w[0] in ‘aeiou’: (ii) SELECT COUNT(*) FROM STUDENT
L1.append(w) WHERE SEX = ‘F’
elif w[0] in ‘AEIOU’: (iii) SELECT STREAM, COUNT(*) FROM
L2.append(w) STUDENT GROUP BY STREAM;
print(“List of words starting with (iv) SELECT NAME, CITY FROM STUDENT,
lowercase vowels”, L1) ADDRESS WHERE STUDENT. AID =
print(“ List of words starting ADDRESS. AID;
with uppercase vowels”, L2) (b) SHOW TABLES;
def main():
counts(“A quick black elephant 29. Write a program to calculate the sum and mean
enters Into a jungle”) of the elements which are entered by user.
Sol :
main()

28. (a) Write SQL commands (i) to (iv) for the list1 = list()
following tables : sum = 0
num = int(input(“Enter the size of
TABLE : STUDENT
the list:”))
S NAME STREAM FEES AGE SEX AID
print(“Enter the number:”)
NO
for i in range (int(num)):
1 ARUN COMPUTER 750.00 17 M A1
l = int(input(“ ”))
KUMAR
list1.append(int(l))
2 DIVYA COMPUTER 750.00 18 F A2
sum = sum + list1[i]
JENEJA
mean = sum/num
3 KESHAR BIOLOGY 500.00 16 M A2
MEHRA
print(“Sum = ”, sum)
print(“Mean = ”, mean)
4 HARISH ENG. DR 350.00 18 M A1
SINGH
30. Write the Push operation of stack containing
5 PRACHI ECONOMICS 300.00 19 F A3 person names. Notice that the name should only
6 NISHA COMPUTER 750.00 15 F A3 accept characters, spaces and period (.) except
ARORA digits. Assume that Pname is a class instance
7 DEEPAK ECONOMICS 300.00 16 M A1 attribute.
KUMAR or
8 SARIKA BIOLOGY 500.00 15 F A1 Find the final contents of a stack that encounters
VASWANI the following tokens.
Assume that an operand is pushed to stack and
TABLE: ADDRESS a binary operator pops two operands from stack
and pushes the result to the stack.
AID City
100,8,3,*,50,2,+,+,*
Al Jamshedpur
Sol :
A2 Kolkata
def insert():
A3 Mumbai name_pattern = re.compile
(i) List the name of all the students, who (r “[A-Za-zs.]”)
have taken stream as COMPUTER. while True :
(ii) To count the number of female students. n = input (“Enter name:”)
(iii) To display the number of students stream while name_pattern. search (n) :
wise. print (“Invalid name”)
(iv) To display names of the students with print (“Enter name correctly”)
corresponding cities. n = input( )
(b) Write the command to display all the tables Sname. append (n)
in the database. c = input (“Enter more name
Page 6 Sample Paper 1 Computer Science Class 12

<y/n>”).upper ( )
Administrative Faculty Studio 120
if (c!=‘y’):
Building Building
break
or Finance Building Faculty Studio 70
Building
Scanned Operation Stack status
Elements Expected computers to be installed in each
building
100 Push 100
8 Push 100, 8 Buildings Computers
3 Push 100, 8, 3 Administrative Building 20
* Pop twice 8 * 3 = 24 100, 24 Finance Building 40
50 Push 100, 24, 50 Faculty Studio Building 120
2 Push 100, 24, 50, 2 (i) Suggest the most appropriate building, where
EPG should plan to install the server.
+ Pop twice 50 + 2 = 100, 24, 52 (ii) Suggest the most appropriate building to
52 building cable layout to connect all three
+ Pop twice 24 + 52 100, 76 buildings for efficient communication.
= 76 (iii) Which type of network out of the following is
* Pop twice 100 * 76 7600 formed by connection the computers of these
= 7600 three buildings?
Output 7600 (a) LAN (b) MAN (c) WAN
(iv) Write the difference between LAN and MAN.
(v) Expand the following
(a) WAN (b) MAN
Section D
Sol :
31. Expertia Professional Global (EPG) in an online (i) EPG should install the server in the Faculty
corporate training provider company for IT Studio Building as it has maximum number
related courses. The company is setting up their of computers.
new campus in Mumbai. You as a network expert (ii)
have to study the physical locations of various
buildings and the number of computers to be
installed. In the planning phase, provide the best
possible answers for the queries (i) to (v) raised
by them.
Physical locations of the buildings of EPG

(iii) (a) LAN (Local Area Network).


(iv) A LAN is a local area network of computers
connected within a small area , such as room
, a building or a campus.
A MAN is a metropolitan area network spread
across a city within a range of approximately
60 KM.
(v) (a) Wide Area Network
Building to building distance (in metre) (b) Metropolitan Area Network

From To Distance 32. (a) Write a Python program to find maximum


and minimum elements in a tuple.
Administrative Finance 60 (b) Consider the table MobileStock with following
Building Building fields
Page 7 Sample Paper 1 Computer Science Class 12

M_Id, M_Name, M_Qty, M_Supplier Step 2 Create the connection object


Write the Python code to fetch all records To create a connection between the MySQL
with fields M_Id, M_Name and M_Supplier database and Python application, use connect()
from database Mobile. method mysql.connector module is used. Pass the
or database details like HostName, UserName and
(a) Which of the following are invalid names and database
why? Password. This method returns the connection
(i) Paidlnterest (ii) S-num object.
(iii) Percent (iv) 123 Syntax
(b) Write the steps for Database connectivity Connection_object
with short explanation of each step. = mysql.connector.connect(
Sol : host = HostName,
user = UserName,
(a) tuple1 = (23,45,-65,-45,20,45,
passwd = password
65,-24)
Step 3 Creating the cursor object
print(“The tuple is:”,tuple1)
The cursor object is used to define as an
min1 = tuple1.index (min(tuple1))
abstraction that specified in Python DB-API 2.0.
max1 = tuple1.index (max(tuple1))
It provides the facility to the user to work on
print(“Maximum element in the tuple
multiple separate environment through the same
is :”, max(tuple1),” at
connection to the database. Cursor object can
index number ”, max1)
be create using cursor 0 method of connection
print(“Minimum element in the tuple
object. It is an important term to the database
is :”, min(tuplel),” at
for executing queries.
index number ” ,min1)
Syntax
(b) import mysql.connector as mydb
cursor_object = connection_object.
myton = mydb.connect (host =
cursor( )
“localhost”, user = “root”,
Step 4 Execute the Query
passwd = “system”, database =
After creating the cursor, SQL query can be
“Mobile”)
execute using execute() function.
cursor = mycon.cursor( )
Syntax
sql = “SELECT M_Id, M_Name, M_Supplier
cursor_object.execute (query)
FROM MobileStock”
Step 5 Clean up the environment
try:
This is the final step for creating, database
cursor. execute (sql)
connectivity. There is necessary to.close the
display = cursor. fetchall ( )
connection which you created.
for i in display
Syntax
print (i)
connection_object.close()
except :
mycon.rollback ( ) 33. What does tell() method do?
mycon.close ( ) (a) AddRegistration() :To accept more student
or registration data and store them to the binary
(a) (i) Valid file keeping the existing registration data.
(ii) Invalid, is not allowed in the variable A Binary file “Registration.dat” exists
name. storing details of students who have been
(iii) Valid registeredfor CBSE board exams. The file
(iv) Invalid, first character must be alphabet. stores following data of students :
(b) There are various steps for creating database RegnNo StudName class No of subjects
connectivity as follows (b) CountRegistrations() : Display count of
Step 1 Import mysql.connector module registrations using the functions.
To import mysql.connector module, write the or
following command : What does seek() method do?
import mysql.connector (a) PutBike() : To accept data of more bikes and
or store them to the file “Bikes.csv”
import mysql.connector as mydb
Page 8 Sample Paper 1 Computer Science Class 12

A CSV file “Bikes.csv” stores details of bikes From: 0 - Beginning of the file
with their brand names, cc and cost. 1 - Current Position
Record structure of “Bikes.csv” 2 - End of the file
BID Bname Brand Cost Program :
(b) SearchBike(bikeid) : To open the file “Bikes. import pickle
csv” and display details of the bike whose def PutBike():
from id is supplied as the parameter to the f=open(“Bikes.csv”, “ab”)
function. ans=‘y’
Sol :
bid=“”
bname=“”
ten() method tells you the current position of brand=“”
cursor within the file. cost=0.0
Syntax file_object.tell() while ans==‘y’:
Program: bid=input(“Enter bike id.”)
import pickle bname=input(“Enter bike name ”)
def AddRegistration(): brand=input(“Enter brand : ”)
f=open(“Registration.dat”, “ab”) cost=float(input(“Enter cost”))
ans=‘y’ blst=[bid, bname, brand,cost]
rno=“” pickle.dump(blst,f)
sname=“” ans=input(“Continue(y/n)”.)
class=“” f,close()
Nos=0 def SearchBike(bikeit):
while ans== ‘y’: f=open(“Bikes:csv,” “rb”)
rno=input(“Enter registration while True:
no..”) try:
sname=input(“Enter student blst=pickle.load(f)
name ”) if blst[0]=bikeid:
class=input(“Enter class”) print(blst)
Nos=int(input(“Enter number of break
subjects :”)) except EOFError:
reglst=[rno,sname,class,Nos] print(“No such bike!!!”)
pickle.dump(reg1st.f) f.close.()
ans=input(“Continue(y/n)”)
f.closec()
def CountRegistrations():
f=open(“Registration.dat”, “rb”)
Section E
count=0
34. Consider the following table ORDERS :
try:
while True: TABLE : ORDERS
phone1st=pickle.load(f)
O_Id OrderDate OrderPrice Customer
count+=1
print(“Number of registrations 1 2008/11/12 1000 Hansen
:”, count) 2 2008/10/23 1600 Nilsen
except EOFError:
break: 3 2008/09/02 700 Hansen
f.close() 4 2008/09/03 300 Hansen
AddRegistration() 5 2008/08/30 2000 Jensen
CountRegistrations()
or 6 2008/10/04 100 Nilsen
seek() method can be used to changes the current (i) Write a statement to create the above table.
file position (ii) Write a command to change the width of
Syntax: Fileobject.seek(offseff[, from]) Customer column to varchar(30)
Offset: number of bytes to be moved. (iii) Write statements to :
Page 9 Sample Paper 1 Computer Science Class 12

(a) Display the field names, their type , size


and constraints .
(b) Display details of orders where orderprice
is in the range 500 to 1500
or (Option for part iii only)
(a) Write a command to increase orderprice
of all orders by 15%.
(b) Name the constraint that will restrict
both NULL and DUPLICATE values in
the O_Id field.
Sol :
(i) CREATE TABLE ORDERS(O_Id
integer(3), OrderDate date,
OrderPrice integer(4),Customer
Varchar(20));
(ii) ALTER TABLE ORDERS MODIFY customer
varchar(30);
(iii) (a) DESCRIBE ORDERS;
(b) SELECT * FROM ORDERS WHERE
OrderPrice BETWEEN 500 AND
1500;
or
(a) UPDATE_ORDERS SET OrderPrice =
OrderPrice + OrderPrice*0.15;
(b) Primary key

35. A user-defined method to open a text file “para.


txt” and write its contents to another file fter
removing the 3rd line
def Func():
with open (‘Para.txt’, ‘r’) as f:
l=f.readlines()
f.close()
print(l)
del l[3]
print(l)
f=open (‘Para.txt’, ‘w’)
f...........
f.close()
(a) Which module needs to be imported to use
operating system functions like rename() and
remove().
(b) Write the function name to open a text file.
(c) Fill the blank as marked in above code.
Sol :
(a) os module
(b) open() function can be used to open a file.
(c) writelines(I)

END
Page 1 Sample Paper 1 Computer Science Class 12

Sample Paper 10 Solutions


Computer Science (083)
CLASS XII 2023-24
Time: 3 Hours Max. Marks: 70
General Instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.

5. The default mode in which a file is opened is


Section A (a) r (b) rw+
(c) w (d) a
1. The output of print(math.ceil(17.34)) is
Sol :
(a) 18 (b) 17
(c) 10 (d) 20 (a) r
Sol : 6. Which attribute is used to return access mode
(a) 18 with that file was opened?
(a) mode.file
2. The...........clause is used in SQL to specify a (b) mode.file.name
range of values. (c) file.mode
(a) WHERE (d) file.mode.type
(b) DROP
Sol :
(c) BETWEEN
(d) RANGE (c) file.mode
Sol : 7. Which of the following is not a DDL command ?
(c) BETWEEN (a) ALTER (b) CREATE
(c) DROP (d) DELETE
3. Two friends have connected their computers , but
Sol :
are getting weak signals. Which device need to be
used to get better signals? (d) DELETE
(a) Repeater (b) Hub
(c) Switch (d) Modem 8. State True or False
‘A dictionary is ordered by index”.
Sol :
Sol :
(a) Repeater
False
4. ______method creates a cursor object while
connecting a Python application with a Mysql 9. The module required to use the mode function is
database. (a) math (b) statistics
(a) connection( ) (b) connect( ) (c) random (d) Pandas
(c) cursor( ) (d) None of these Sol :
Sol : (b) statistics
(c) cursor()
Page 2 Sample Paper 1 Computer Science Class 12

10. The.........command can be used to remove all 16. The first integrity rule for relational databases
records of a table along with the table structure. ensures that_____
(a) DELETE TABLE (a) Primary key is unique
(b) DROP TABLE (b) Foreign key is unique
(c) REMOVE TABLE
(d) None of these (c) Primary key is unique and NOT NULL

Sol : (d) There is only one candidate key

(b) DROP TABLE Sol :

11. What is the output of the following code? (c) Primary key is unique and NOT NULL
>>> a = 10
Directions (Q.Nos. 17-18) are Assertion and
>>> b = 2
Reason based questions.
>>> print(a + 10 * 2 + b)
(a) 32 (b) 22 17. Assertion (A) User-defined functions must stay in
(c) 40 (d) 80 a Python module.
Sol : Reason (R) Each user-defined function must stay
in a module ,which is linked to a folder where all
(a) 32 the user defined functions of the module stay.
12. Which function is used to generate a sequence of (a) Both A and R are true and R is the correct
numbers overtime? explanation for A.
(a) range() (b) len() (b) Both A and R are true but R is not the
(c) limit() (d) lim() correct explanation for A.
Sol : (c) A is true but R is false.
(a) range() (d) A is false but R is true.

13. Which of the following symbol is used in Python Sol :


for comments? (a) Both A and R are true and R is the correct
(a) $ (b) @ explanation for A.
(c) // (d) #
Sol : 18. Assertion (A) Python supports addition of data
in file , preserving the previous data.
(d) # Reason (R) The write mode erases all previous
data of a pre-existing file.
14. Given a list Lst= [65,182,90,420,20,10]. What
(a) Both A and R are true and R is the correct
will be the correct statement to take out the 3rd
explanation for A.
element from the list?
(a) Lst.pop(2) (b) L.find(2) (b) Both A and R are true but R is not the
(c) L.pop(–1) (d) L.del(90) correct explanation for A.
Sol : (c) A is true but R is false.
(a) Lst.pop(2) (d) A is false but R is true.

15. The relation between Primary key , Candidate Sol :


key and Alternate key is (b) Both A and R are true but R is not the correct
(a) Primary key = Candidate key - Alternate key explanation for A.
(b) Candidate key= Primary key - Alternate key
(c) Alternate key= Primary key+ Candidate key
(d) None of the above
Sol :
(a) Primary key = Candidate key - Alternate key
Page 3 Sample Paper 1 Computer Science Class 12

print(i)
Section B i=i*2

19. Write the corresponding Python expression for Sol :


the following mathematical expression. (a) The valid identifiers are:
(i) z= a/a+ b – d2
Identifier Reason
(ii) z= x2 + y3
name_1 Digits and underscore is allowed
Sol :
along with alphabets
(i) z= a/(a+b)–(d*d)
SUM Underscore at the first position is
(ii) z=(x**2)+(y**3)
allowed
20. Mr. GopiNath Associate Manager of Unit. The invalid identifiers are:
Nations corporate recently discovered that the Identifier Reason
communication between his company’s accounts
$sum $ sign can be used in other
office and HR office is extremely slow and signals
programming languages for
drop quite frequently. These offices are 120
creating identifier, however
metre away from each other and connected by an
Python does not support $ sign
Ethernet cable.
(i) Suggest him a device which can be installed in num^2 Special character are not allowed
between the office for smooth communication. (b) Output
(ii) What type of network is formed by having 1 2 4
this kind of connectivity out of LAN, MAN
and WAN? 22. Differentiate between char(n) and varchar(n)
or data types with respect to databases.
Define hub and write its functions and types. Sol :
Sol : Differences between char(n) and varchar(n) are
as follows
(i) The device that can be installed between the
office for smooth communication is repeater. char(n) varchar(n)
(ii) The type of network is Local Area Network It stores a fixed length It stores a variable
(LAN). string between 1 and length string.
or 255 characters.
A hub connects several computers together and
acts as a central node or server. If the value is of No blanks are added
Function of a hub smaller length, then it by varchar(n) even
(i) Interconnects number of computers or users. adds blank spaces. if value is of smaller
(ii) All the incoming data packets received by length.
the hub are send to all hub ports and from Some space is wasted No wastage of space in
their, the data is sent to all the computers, in it. varchar(n).
connected in a hub network.
Hub are of two types 23. (a) Mention any two advantages of E-mail over
(i) Active hub It acts as repeater. It amplifies conventional, mail.
the signal as these move from one device to (b) Mr. Lal owns a factory which manufactures
another. automobile spare parts. Suggest him the
(ii) Passive hub It simply passes the signal from advantages of having a web page for his
one connected device to another. factory
Sol :
21. (a) Determine which of the following identifiers
are valid. If invalid, explain with reason. (a) Advantages
(i) name_1 (ii) _SUM (1) E-mail is extremely cost effective.
(iii) $Sum (iv) num ^ 2 (2) E-mail takes lesser time for transmitting
(b) Find the output of the following code data than conventional mail.
i=1 (b) The web page provides the information to
while (i<5): the clients about his factory of spare parts.
Page 4 Sample Paper 1 Computer Science Class 12

Moreover, he can receive the order on the Section C


Internet from the client using the web page.

24. Name the tokens that are available in Python. 26. Consider the tables FAMILY and Occupation:
or TABLE FAMILY
Find the syntax error in the following program
No Name Female Male Income Occup-
and underline after correct them. Members Members ationId
90 = w
1 Mishra 3 2 7000 O1
while(w > 60)
2 Gupta 4 1 50000 O2
print(w)
w = w – 50 3 Khan 6 3 8000 O2
4 Chaddha 2 2 25000 O1
Sol :
5 Yadav 7 2 20000 O3
Python has the following tokens
(i) Identifiers 6 Joshi 3 2 14000 O2
(ii) Keywords 7 Maurya 6 3 5000 O1
(iii) Punctuators 8 Rao 5 2 10000 O3
(iv) Literals
(v) Operators
Table : OCCUPATION
or
Correct code is Occupationld Type
w = 90 O1 Service
whi1e(w>60):
O2 Business
print(w)
w = w – 50 O3 Mixed
(a) To display Family name , corresponding
25. Explain the use of ORDER BY clause.
occupation and income where male members
or
are more than 2.
What are DDL and DML?
(b) Write SQL queries for statements (i) to (iv)
Sol : based on tables FAMILY and Occupation.
The ORDER BY keyword is used to sort the (i) To select all the information of family,
result set along a specified column with the whose Occupation is Service.
SELECT command. (ii) To list the name of family, where female
The ORDER BY keyword sorts the records in members are more than 3.
ascending order by default. If you want to sort (iii) To list all names of family with income in
the records in a descending order, you can use the ascending order.
DESC keyword. (iv) To count the number of family, whose
Syntax income is less than 10000.
SELECT column_name(s) Sol :
FROM table_name
(a) SELECT Name, Type,Income FROM
ORDER BY column_name(s) ASC/DESC;
FAMILY F, OCCUPATION 0 WHERE
or
F.Occupationld= 0.0ccupationID
DDL (Data Definition Language) is a part of
where MaleMembers>2;
SQL, which provides commands for creating,
(b) (i) SELECT * FROM FAMILY
altering and dropping the tables. Different DDL
F,OCCUPATION 0 WHERE
commands are CREATE, ALTER, DROP and
F.OccupationId=0.0ccupationId
RENAME.
= ‘Service’;
DML (Data Manipulation Language) is a part
(ii) SELECT Name FROM FAMILY WHERE
of SQL, which provides commands for inserting,
FemaleMembers > 3;
deleting and updating the information in a
(iii) SELECT Name, Income FROM FAMILY
database. Different DML commands are SELECT,
ORDER BY Income;
UPDATE, INSERT.
(iv) SELECT COUNT(*) FROM FAMILY
WHERE Income < 10000;
Page 5 Sample Paper 1 Computer Science Class 12

27. Write a method countFile() to count and display consonant.append(w)


the number of lines starting with the word ‘FILE’ elif w[-1] in ‘aeiou’:
(including small cases and upper cases) present in vowel.append(w)
a text file “start.txt”. print(“List of words ending with
e.g. If the file “start.txt” contains the following vowels”, vowel)
lines: print(“List of words ending with
Get the data value to be deleted, consonants ”, consonant)
Open the file for reading from it.
28. (a) Study the following tables DOCTOR and
Read the complete file into a list
SALARY and write SQL commands for the
Delete the data from the list
questions (i) to (iv).
Open the file
Open same file for writing into it TABLE: DOCTOR
Write the modified list into file.
ID NAME DEPT SEX EXPER-
Close the file.
IENCE
The method should display
Total lines started with word ‘FILE’ is/are: 0 101 John ENT M 12
or 104 Smith ORTHOPEDIC M 5
Write definition of a function that takes input a 107 George CARDIOLOGY M 10
sentence and display the list of words that end 114 Lara SKIN F 3
with a lowercase vowel and list of words that end
109 K George MEDICINE F 9
with a lowercase consonant
105 Johnson ORTHOPEDIC M 10
Sol :
117 Lucy ENT F 3
import os
111 Bill MEDICINE F 12
def countFile():
130 Morphy ORTHOPEDIC M 15
if os.path.isfile(“start.txt”):
f=open(“start.txt”, “r”)
c=0 TABLE: SALARY
print(“The lines are:”) ID BASIC ALLOWANCE CONSULTATION
while True: 101 12000 1000 300
l=f.readline()
104 23000 2300 500
l=l.rstrip()
print(l) 107 32000 4000 500

if not l: 114 12000 5200 100


break 109 42000 1700 200
list1=l.upper().split() 105 18900 1690 300
if(list1[0]==‘FILE’):
130 21700 2600 300
c=c+1
if(c>0): (i) Display NAME of all doctors who are
print(“Total lines started with in MEDICINE department having more
the word ‘FILE’ is/are:”, c) than 10yrs experience from the table
else: DOCTOR.
print(“There is no line started (ii) Display the average salary of all doctors
with the word ‘FILE’ ”) working in ENT department using the
f.close() tables DOCTOR and SALARY. SALARY
else: = BASIC + ALLOWANCE.
print(“File does not exist”) (iii) Display the minimum ALLOWANCE of
or female doctors.
def vowelconsonant(sen): (iv) Display the highest consultation fee
vowel=[ ] among all male doctors.
consonant=[ ] (b) Write the command to change the data type
for w in sen.split(‘ ’): of consultation to double(8,3).
if w[-1] not in ‘aeiou’: Sol :
Page 6 Sample Paper 1 Computer Science Class 12

(a) (i) SELECT NAME FROM DOCTOR WHERE while True :


DEPT = ‘MEDICINE’ AND EXPERIENCE n = input (“Enter name:”)
> 10; while name_pattern. search (n) :
(ii) SELECT AVG(BASIC + ALLOWANCE) print (“Invalid name”)
FROM SALARY WHERE SALARY.ID print (“Enter name correctly”)
IN(SELECT ID FROM DOCTOR WHERE n = input( )
DEPT = ‘ENT’); Sname. append (n)
(iii) SELECT MIN(ALLOWANCE) FROM c = input (“Enter more name <y/n>”).
SALARY WHERE SALARY.ID upper( )
IN(SELECT ID FROM DOCTOR WHERE if (c! = ‘y’):
SEX ‘F’); break
(iv) SELECT MAX(CONSULTATION) insert()
FROM SALARY WHERE SALARY.ID or
IN(SELECT ID FROM DOCTOR WHERE Scanned Operation Stack status
SEX = ‘M’); Elements
(b) ALTER TABLE SALARY MODIFY
100 Push 100
consultation double(8,3);
8 Push 100, 8
29. Write a program to count the frequency of
3 Push 100, 8, 3
elements in a list entered by user.
* Pop twice 8 * 3 = 24 100, 24
Sol :
50 Push 100, 24, 50
a = [ ]
n = int(input(“Enter number of 2 Push 100, 24, 50, 2
elements:”)) + Pop twice 50 + 2 = 100, 24, 52
for i in range(1, n + 1): 52
b = int(input(“Enter element:”))
+ Pop twice 24 + 52 100, 76
a.append (b)
= 76
k = 0
num = int(input(“Enter the number to * Pop twice 100 * 76 = 7600
be counted:”)) 7600
for j in a : Output 7600
if (j == num):
k = k + 1
print (“Number”, num, “is appear”, Section D
k, “times.”)
31. Workalot consultants are setting up a secured
30. Write the Push operation of stack containing
network for their office campus of Gurgaon for
person names. Notice that the name should only
their day-to-day office and web based activities.
accept characters, spaces and period (.) except
They are planning to have connectivity between 3
digits. Assume that Pname is a class instance
buildings and the head office situated in Mumbai.
attribute.
Answer the questions (i) to (v) after going through
or
the building positions in the campus and other
Find the final contents of a stack that encq]lnters
details, which are given below:
the following tokens.
Assume that an operand is pushed to stack and
a binary operator pops two operands from stack
and pushes the result to the stack.
(100, 8, 3, *, 50, 2, +, +, *)
Sol :
def insert():
name_pattern = re.compile
(r “[A-Za-zs.]”)
Page 7 Sample Paper 1 Computer Science Class 12

(iii) (a) Switches are needed in every building


as they help share bandwidth in every
Distance between various buildings building.
Building GREEN to Building RED 110 m (b) Repeaters may be skipped as per above
layout (because distance is less than 100
Building GREEN to Building BLUE 45 m m), however if building GREEN and
Building BLUE to Building RED 65 m building RED are directly connected, we
can place a repeater there as the distance
Gurgaon Campus to Head Office 1760 km
between these two buildings is more than
Number of computers 100 m.
(iv) A Modem is a network device that converts
Building GREEN 32
Analog signals to Digital and Digital to
Building RED 150 Analog.
Building BLUE 45 (v) Firewall prevents the unauthorised access in
the network.
Head Office 10
(i) Suggest the most suitable place (i.e. building) 32. (a) Write a Python program to concatenate
to house the server of this organisation. following dictionaries to create a new one.
Also, give a reason to justify your suggested d1={‘A’:10, ‘B’:20}
location. d2={‘C’:30, ‘D’:40}
(ii) Suggest a cable layout of connections between d3={‘E’:50, ‘F’:60}
the buildings inside the campus. (b) Consider the table MobileStock with following
(iii) Suggest the placement of the following devices fields
with justification : M_Id, M_Name, M_Qty, M_Supplier
(a) Switch Write the Python code to fetch all records
(b) Repeater with fields M_Id, M_Name and M_Supplier
(iv) Write the use of Modem in a network. from database Mobile.
(v) What is the use of firewall in network? or
(a) Sohan has a list containing 8 integers as marks
Sol :
of subject Science. You need to help him to
(i) Building RED is the suitable place to house create a program with separate user defined
the server because it has maximum number of function to perform the following operations
computers. based on the list.
(ii) (i) Push those marks into a stack which are
greater than 75.
(ii) Pop and display the content of the stack.
Simple Input
Marks = [75, 80, 56, 90, 45, 62, 76, 72]
Sample Output
80 90 76
(b) Consider the following table Traders with
following fields
Page 8 Sample Paper 1 Computer Science Class 12

TCode TName City (b) import mysql. connector


mycon = mysql.connector.connect
T01 Electronic Sales Mumbai (host = “localhost”, user = “root”,
T03 Busy Store Corp Delhi passwd = “system”,
T02 Disp House Inc Chennai
database = “Admin”)
cursor = mycon. cursor ( )
Write Python code to display the names of those sql = “SELECT * FROM Traders WHERE
traders who are either from Delhi or from Mumbai. City = ‘Mumbai’ OR City = ‘Delhi’”
Sol : try:
cursor.execute(sql)
(a)
dis = cursor.fetchall ( )
d1 = {‘A’:10, ‘B’:20}
for i in disp:
d2 = {‘C’:30, ‘D’:40}
print (i)
d3 = {‘E’:50, ‘F’:61}
except :
d4= { }
mycon.rollback ( )
for i in (d1, d2, d3):
mycon.close ( )
d4.update(i)
print(d4) 33. What is difference between tell() and seek()
(b) import mysql.connector as mydb methods?
mycon = mydb.connect (host = A Binary file “lottery.dat” stores details of lottery
“localhost”, user=“root”, passwd = ticket holders . The file stores the following details
“system”, database = “Mobile”) :
cursor = mycon.cursor ( ) TicketNo State Type Prizemoney
sql = “SELECT M_Id, M_Name, Write a program using two functions to operate
M_Supplier FROM MobileStock” the file data.
try: (a) AddBuyers(State) : To accept more ticket
cursor. execute (sql) details and store them into the file only if the
display = cursor. fetchall () ticket is not from state passed as parameter
for i in display to the function.
print (i) (b) TicketSearch(tid) : To open the file “lottery.
except : dot” and display details of the ticket whose id
mycon.rollback ( ) is supplied as the parameter to the function.
mycon.close ( ) or
or Compare text files and binary files.
(a) A Binary file “car.dat” stores details of cars. The
Marks = [75, 80, 56, 90, 45, 62, 76, file stores the following details :
72] CarNo Brand Kms Cost
def PUSH (St, Marks): Write a program using two functions to operate
St. append(Marks) the file data.
def POP(St): (a) AddCardata() : To accept car details and
if St! = [ ]: store them into the file “car.dat”
return St. pop ( ) (b) CarReport() : To open the file “car.dat” and
else; display details of the cars who have run more
return None than 100000 kilometres.
Stack1 = [ ]
for x in Marks: Sol :
if x >75 : tell() method returns the current position of
PUSH (Stack1, x) cursor in file while seek() method changes the
while True: cursor bytes as specified by the offset.
if Stackl! =[ ] Program:
print (POP(Stack1), end = “ ”) import pickle
else: def AddBuyers(State):
break f=open(“lottery.dat ”, “ab”)
ans=‘y’
Page 9 Sample Paper 1 Computer Science Class 12

tid=“” ”))
st=“” clst=[cno,bd,kms,cost]
type=“” pickle.dump(clst,f)
pmoney=0.0 ans=input(“Continue(y/n)”)
while ans==‘y’: f.close()
tid=input(“Enter ticket id”) def CarReport():
st=input(“Enter state name ”) f=open(“car.dat ”,“rb”)
type=input(“Enter ticket type while True:
: ”) try:
pmoney=float(input(“Enter clst=pickle.load(f)
prizemoney ”) if int(tlst{2] > 100000):
tlst=[tid, st, type,pmoney] print(clst)
if st=State: break
pickle.dump(tlst,f) except EOFError:
ans=input(“Continue(y/n)”) print(“No such ticket!!!”)
f.close() f.close()
def TicketSearch(tid): AddCardata()
f=open(“lottery.dot”,“rb”) CarReport()
while True:
try:
tlst=pickle.load(f) Section E
if tlst[0]==tid:
print(tlst) 34. Consider the following table FLIGHTS :
break
except EOFError; TABLE : FLIGHTS
print(“No such ticket!!!”) FL_NO STARTING ENDING NO_ NO_
f.close() FLIGHT STOPS
AddBuyers(State) IC301 MUMBAI DELHI 8 0
TicketSearch(tid) IC799 BENGALURU DELHI 2 1
or
MC101 INDORE MUMBAI 3 0
Text Files Binary Files IC302 DELHI MUMBAI 8 0
1 It is capable to It is capable to AB812 KANPUR BENGALURU 3 1
handle textual data. handle large file. IC899 MUMBAI KOCHI 1 4
2 It consists of series It consists of data AM501 DELHI TRIVANDRUM 1 5
of lines of a set of with a specific
MU499 MUMBAI MADRAS 3 3
letters, numbers or pattern without any
IC701 DELHI AHMEDABAD 4 0
symbols (String) delimiter.
Program: (i) The command to create the table was written
import pickle as :
def AddCardata(): Create table FLIGHTS( FL_NO integer,
f=open(“car.dat”, “wb”) STARTING char(20), ENDING char(30),
ans=‘y’ NO_FLIGHT integer, NO_STOPS integer);
cno=“” What is wrong with command ?
bd=“” (ii) What is the cardinality of the table ?
kms=0.0 (iii) Which functions will be used to :
cost=0.0 (a) Display total number of flights .
while ans==‘y’: (b) Display number of flights whose FL_NO
cno=input(“Enter car number :”) starts with “IC”
bd=input(“Enter brand name : ”) (option for part (iii) only)
kms=float(input(“Enter kilometers Write function names to :
: ”)) (a) Show the average Number of stops.
cost=float(input(“Enter cost : (b) Show the maximum number of stops.
Page 10 Sample Paper 1 Computer Science Class 12

Sol :
(i) Create table FLIGHTS( FL_NO varchar(10),
STARTING char(20), ENDING char(30) ,
NO_FLIGHT integer , NO_STOPS integer);
(ii) 9 – Cardinality is the number of tuples or
rows in a table.
(iii) (a) SUM()
(b) COUNT()
or
(a) AVG()
(b) MAX()

35. A user-defined method to open a text file ‘Author.


txt” and display the lines that have even number
of words.
def evenwords():
f=open(“Author.txt”)
ln=f.readlines()
for line in ln:
linex=............// Statement
if len(linex)%2==0:
print(line)
f.close()
(a) How is readline() method different from
readlines() method in Python?
(b) Write the use of the reader object in csv file
operations.
(c) Fill the blank as marked statement.
Sol :
(a) The readline() method reads a line as a string
. The readlines() method reads all the lines of
the file into a list, with each line as an item of
the list.
(b) The reader object can be used to read all
the records from the csv file , from which the
the records may be operated in a loop on the
reader object.
(c) line.split (‘ ’)

END

You might also like