0% found this document useful (0 votes)
56 views230 pages

Class 12 Cs All KV Region Papers 2022-23 Removed

The document is a pre-board examination paper for Class XII in Computer Science, organized by Kendriya Vidyalaya Sangathan Agra Region. It consists of five sections with various types of questions, including true/false, multiple-choice, and programming tasks, all to be answered in Python. The exam is designed to assess students' understanding of computer science concepts and their practical application.

Uploaded by

SHADOW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views230 pages

Class 12 Cs All KV Region Papers 2022-23 Removed

The document is a pre-board examination paper for Class XII in Computer Science, organized by Kendriya Vidyalaya Sangathan Agra Region. It consists of five sections with various types of questions, including true/false, multiple-choice, and programming tasks, all to be answered in Python. The exam is designed to assess students' understanding of computer science concepts and their practical application.

Uploaded by

SHADOW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SET-1

KENDRIYA VIDYALAYA SANGATHAN AGRA REGION


PRE BOARD EXAMINATION 2022-23

Class : XII Time Allowed : 03:00 Hours


Subject : (083) Computer Science Maximum Marks : 70

General instructions:
• This question paper contains five sections, Section A to E.
• All questions are compulsory.
• Section A have 18 questions carrying 01 mark each.
• Section B has 07 Very Short Answer type questions carrying 02 marks each.
• Section C has 05 Short Answer type questions carrying 03 marks each.
• Section D has 03 Long Answer type questions carrying 05 marks each.
• Section E has 02 questions carrying 04 marks each. One internal choice is given in Q34 against part C only.
• All programming questions are to be answered using Python Language only.

Section – A
Q01. State True or False (1)
“Tuple is datatype in Python which contain data in key-value pair.”

Q02. Which of the following is not a keyword? (1)


(A) eval (B) assert
(C) nonlocal (D) pass

Q03. Given the following dictionaries (1)


dict_student = {"rno" : "53", "name" : ‘Rajveer Singh’}
dict_marks = {"Accts" : 87, "English" : 65}
Which statement will merge the contents of both dictionaries?
(A) dict_student + dict_marks (B) dict_student.add(dict_marks)
(C) dict_student.merge(dict_marks) (D) dict_student.update(dict_marks)
Q04. Consider the given expression: (1)
not ((True and False) or True)

Page 1 of 14 | KVS – Regional Office AGRA | Session 2022-23


Which of the following will be correct output if the given expression is evaluated?
(A) True (B) False
(C) NONE (D) NULL
Q05. Select the correct output of the code: (1)
>>> s='[email protected]'
>>> s=s.split('kv')
>>> op = s[0] + "@kv" + s[2]
>>> print(op)
(A) mail2@kvsangathan (B) mail2@sangathan.

(C) mail2@kvsangathan. (D) mail2kvsangathan.


Q06. Which functions is used to close a file in python? (1)
(A) close (B) cloose()
(C) Close() (D) close()
Q07. Fill in the blank: (1)
________ command is used to change table structure in SQL.
(A) update (B) change
(C) alter (D) modify
Q08. Which of the following commands will remove the entire database from MYSQL? (1)
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
Q09. Which of the following statement(s) would give an error after executing the following code? (1)
D={'rno':32,'name':'Ms Archana','subject':['hindi','english','cs'],'marks':(85,75,89)} #S1
print(D) #S2
D['subject'][2]='IP' #S3
D['marks'][2]=80 #S4
print(D) #S5
(A) S1 (B) S3
(C) S4 (D) S3 and S4
Q10. Fill in the blank: (1)
_____ is a non-key attribute, whose values are derived from the primary key of some other table.
(A) Primary Key (B) Candidate Key
(C) Foreign Key (D) Alternate Key

Page 2 of 14 | KVS – Regional Office AGRA | Session 2022-23


Q11. The correct syntax of seek() is: (1)
(A) seek(offset [, reference_point]) (B) seek(offset, file_object)
(C) seek.file_object(offset) (D) file_object.seek(offset [, reference_point])
Q12. Fill in the blank: (1)
The SELECT statement when combined with ________ clause, returns records without
repetition.
(A) DISTINCT (B) DESCRIBE
(C) UNIQUE (D) NULL
Q13. Fill in the blank: (1)
______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP
(C) PPP (D) HTTP
Q14. What will the following expression be evaluated to in Python? (1)
print ( round (100.0 / 4 + (3 + 2.55) , 1 ) )
(A) 30.0 (B) 30.55
(C) 30.6 (D) 31
Q15. Which function is used to display the total number of records from a table in a database? (1)
(A) total() (B) total(*)
(C) return(*) (D) count(*)
Q16. In order to open a connection with MySQL database from within Python using mysql.connector (1)
package, __________ function is used.
(A) open (B) connect
(C) database() (D) connectdb()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is false but R is True
Q17. str1= “Class” + ”Work” (1)
ASSERTION: Value of str1 will be “ClassWork”.
REASONING: Operator ‘+’ adds the operands, if both are numbers & concatenates the string if
both operands are strings.

Page 3 of 14 | KVS – Regional Office AGRA | Session 2022-23


Q18. Assertion: CSV (Comma Separated Values) is a file format for data storage which looks like a (1)
text file.
Reason (R): The information is organized with one record on each line and each field is separated
by semi-colon.
Section – B
Q19. Vivek has written a code to input a number and check whether it is even or odd number. His code (2)
is having errors. Rewrite the correct code and underline the corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int( input(“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)

Q20. Write two points of difference between Bus topology and star topology. (2)
OR
Write two points of difference between XML and HTML.

Q21. (A) Given is a Python string declaration: (2)


message='FirstPreBoardExam@2022-23'
Write the output of: print(message[ : : -3].upper())

(B) Write the output of the code given below:


d1={'rno':25, 'name':'dipanshu'}
d2={'name':'himanshu', 'age':30,'dept':'mechanical'}
d2.update(d1)
print(d2.keys())

Q22. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give example to (2)

Page 4 of 14 | KVS – Regional Office AGRA | Session 2022-23


support your answer.

Q23. (A) Write the full forms of the following: (2)


(i) HTTP (ii) FTP
(B) What is the use of TELNET?

Q24. Predict the output of the Python code given below: (2)
data=["L",20,"M",40,"N",60]
times=0
alpha=""
add=0

for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] + "@"
add = add + data[c]
print (times, add, alpha)

OR

Predict the output of the Python code given below:


L=[1,2,3,4,5]
Lst=[]
for i in range(len(L)):
if i%2==1:
t=(L[i],L[i]**2)
Lst.append(t)
print(Lst)

Q25. Differentiate between order by and group by clause in SQL with appropriate example. (2)

OR

Page 5 of 14 | KVS – Regional Office AGRA | Session 2022-23


Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP
Section – C
Q26. Write the output of the queries (i) to (vi) based on the table given below: (3)
TABLE: CHIPS

BRAND_NAME FLAVOUR PRICE QUNATITY

LAYS ONION 10 5
LAYS TOMATO 20 12
UNCLE CHIPS SPICY 12 10
UNCLE CHIPS PUDINA 10 12
HALDIRAM SALTY 10 20
HALDIRAM TOMATO 25 30

(i) Select BRAND_NAME, FLAVOUR from CHIPS where PRICE <> 10;
(ii) Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
(iii) Select BRAND_NAME from CHIPS where price > 15 and QUANTITY < 15;
(iv) Select count( distinct (BRAND_NAME)) from CHIPS;
(v) Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
(vi) Select distinct (BRAND_NAME) from CHIPS order by BRAND_NAME desc;
Q27. Write a function countINDIA() which read a text file ‘myfile.txt’ and print the frequency (3)
of the words ‘India’ in it (ignoring case of the word).
Example: If the file content is as follows:

INDIA is my country. I live in India. India has many states.

The countIndia() function should display the output as:


Frequency of India is 3

OR

Write a function countVowel() in Python, which should read each character of a text file
“myfile.txt” and then count and display the count of occurrence of vowels (including small cases

Page 6 of 14 | KVS – Regional Office AGRA | Session 2022-23


and upper case).
Example:
If the file content is as follows:

INDIA is my country. I live in India. India has many states.

The countVowel() function should display the output as:


Total number of vowels are : 20
Q28. (A) Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”. Write (3)
SQL commands for the statements (i) to (iv).
Table: BOOKS
BID BNAME AUNAME PRICE TYPE QTY
COMP11 LET US C YASHWANT 350 COMPUTER 15
GEOG33 INDIA MAP RANJEET P 150 GEOGRAPHY 20
HIST66 HISTORY R BALA 210 HISTORY 25
COMP12 MY FIRST C VINOD DUA 330 COMPUTER 18
LITR88 MY DREAMS ARVIND AD 470 NOBEL 24

Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15
(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been issued.

(B) Write the command to view all tables in a database.


Q29. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as (3)
argument to the function. The function returns another list named ‘indexList’ that stores the
indices of all four lettered word of L.
For example:

Page 7 of 14 | KVS – Regional Office AGRA | Session 2022-23


If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
Q30. A list contains following record of a student: (3)
[StudentName, Class, Section, MobileNumber]
Write the following user defined functions to perform given operations on the stack named ‘xiia’:
(i) pushElement() - To Push an object containing name and mobile number of students who
belong to class xii and section ‘a’ to the stack
(ii) popElement() - To Pop the objects from the stack and display them. Also, display “Stack
Empty” when there are no elements in the stack.
For example:
If the lists of students details are:
[“Rajveer”, “99999999999”,”XI”, “B”]
[“Swatantra”, “8888888888”,”XII”, “A”]
[“Sajal”,”77777777777”,”VIII”,”A”]
[“Yash”, “1010101010”,”XII”,”A”]

The stack “xiia” should contain


[“Swatantra”, “8888888888”]
[“Yash”, “1010101010”]

The output should be:


[“Yash”, “1010101010”]
[“Swatantra”, “8888888888”]
Stack Empty

OR

Write a function in Python, Push(SItem) where, SItem is a dictionary containing the details of
stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater than 25.
Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:

Page 8 of 14 | KVS – Regional Office AGRA | Session 2022-23


Ditem = {“Rubber”:5, "Pencil":5, "Pen":30, "Notebook": 60, "Eraser":5, “Watch”: 250}
The stack should contain
Pen
Notebook
Watch
The output should be:
The count of elements in the stack is 3
Section – D
Q31. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web based (5)
activities. The company compound has 4 buildings as shown in the diagram below:

Orbit
Building
Sunrise
Jupiter
Building
Building

Oracle
Building

Distance between various buildings.


Jupiter Building to Orbit Building 50 Mtrs
Orbit Building to Oracle Building 85 Mtrs.
Oracle Building to Sunrise Building 25 Mtrs.
Sunrise Building to Jupiter Building 170 Mtrs.
Jupiter Building to Oracle Building 125 Mtrs.
Orbit Building to Sunrise Building 45 Mtrs.

Number of Computers in each of the buildings is follows:


Jupiter Building 30
Orbit Building 150

Page 9 of 14 | KVS – Regional Office AGRA | Session 2022-23


Oracle Building 15
Sunrise Building 35

i) Suggest a cable layout of connections between the buildings.


ii) Suggest the most suitable place (i.e. building) to house the server of this organisation with a
suitable reason
iii) Suggest the placement of the following devices with justification:
a. Internet Connecting Device/Modem
b. Switch
iv) The organisation is planning to link its sale counter situated in various parts of the same city,
which type of network out of LAN, MAN or WAN will be formed? Justify your answer.
v) What do your mean by PAN? Explain giving example.
Q32. (A) Write the output of the code given below: (2+3)
def printMe(q,r=2):
p=r+q**3
print(p)

#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)

(B) The code given below inserts the following record in the table Student:
RollNo Name Clas Marks
Integer String Integer Integer
Note the following to establish connectivity between Python and MySQL:
* Username is root
* Password is toor@123
* The table exists in a “stud” database.
* The details (RollNo, Name, Clas and Marks) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object

Page 10 of 14 | KVS – Regional Office AGRA | Session 2022-23


Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3 - to add the record permanently in the database
import mysql.connector as mysql
def sqlData():
con1=mysql.connect(host="localhost",user="root", password="toor@123", database="stud")
mycursor = ________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
clas=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values({},'{}',{},{})".format(rno,name,clas,marks)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")

OR
(A) Predict the output of the code given below:
s="C++VsPy"
m=""
for i in range(0, len(s)):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)

(B) The code given below reads the following record from the table named student and displays
only those records who have marks greater than 90:
RollNo Name Clas Marks

Page 11 of 14 | KVS – Regional Office AGRA | Session 2022-23


Integer String Integer Integer

Note the following to establish connectivity between Python and MySQL:


* Username is root
* Password is toor@123
* The table exists in a “stud” database.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose marks are greater
than 90.
Statement 3- to read the complete result of the query (records whose marks are greater than 90)
into the object named data, from the table student in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",password="toor@123", database="stud")
mycursor=_______________ #Statement 1
print("Students with marks greater than 90 are : ")
______________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()

Q33. What is the advantage of using a csv file for permanent storage? (5)
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of a teacher to a CSV file ‘teacher.csv’. Each record consists
of a list with field elements as tid, name and mobile to store teacher id, teacher name and teacher
mobile number respectively.
(ii) COUNTRECORD() – To count the number of records present in the CSV file named
‘teacher.csv’.
OR
Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:

Page 12 of 14 | KVS – Regional Office AGRA | Session 2022-23


(i) add() – To accept and add data of an employee to a CSV file ‘employee.csv’. Each record
consists of a list with field elements as eid, name and salary to store employee id, employee name
and employee salary respectively.
(ii) search()- To display the records of the employee whose salary is more than 40000.
Section – E
Q34. Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation of the (1+
table, she has entered data of 8 items in the table. 1+
2)
Table : STOCK
stockid dopurchase name make Price
101 2020-07-06 CPU ACER 12000
102 2020-09-01 CPU ACER 12750
103 2020-09-01 MONITOR ACER 7500
104 2016-08-03 PROJECTOR GLOBUS 37250
105 2016-05-26 VISUALIZER GLOBUS 17500
106 2020-07-23 WIFI RECEIVER ZEBION 450
107 2015-02-18 PRINTER LEXMARK 38000
108 2020-07-23 HEADPHONE BOAT 750

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If three columns are added and 5 rows are deleted from the table stock, what will be
the new degree and cardinality of the above table?
(iii) Write the statements to:
(a) Insert the following record into the table
Stockid - 201, dateofpurchase – 18-OCT-2022, name – neckphone
Make – BoAT, price - 500
(b) Decrease the price of stock by 5% whose were purchased in year 2020
OR (Option for part iii only)
(iii) Write the statements to:
(a) Delete the record of stock which were purchased before year 2015.
(b) Add a column STATUS in the table with datatype as char with 1 characters
Q35. Vishnu is a Python programmer. He has written a code and created a binary file record.dat with (1+
studentid, subjectcode and marks. The file contains 10 records. 1+
He now has to update a record based on the studentid id entered by the user and update the marks. 2)
The updated record is then to be written in the file temp.dat. The records which are not to be

Page 13 of 14 | KVS – Regional Office AGRA | Session 2022-23


updated also have to be written to the file temp.dat. If the student id is not found, an appropriate
message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement given
above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
sid=int(input("Enter student id to update his marks :: "))
while True:
try:
rec = ______________ #Statement 3
if rec["studentid"]==sid:
found=True
rec["marks"]=int(input("Enter new marks :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print ("The marks of studentid ", sid ," has been updated.")
else:
print("No student with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
(iii) Which statement should Aryan fill in Statement 3 to read the data from the binary file,
record.dat and in Statement 4 to write the updated data in the file, temp.dat?
0-O-o- End of Paper –o-O-0

Page 14 of 14 | KVS – Regional Office AGRA | Session 2022-23


KENDRIYA VIDYALAYA SANGATHAN
BENGALURU REGION
FIRST PRE-BOARD EXAM (SESSION 2022-23)

CLASS: XII MAX MARKS:70


SUBJECT: COMPUTER SCIENCE TIME: 3 HOURS
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in
Q35 against part c only.
8. All programming questions are to be answered using Python Language only
SECTION A
1. State True or False 1
“Python has a set of keywords that can also be used to declare variables”
2. Which of the following is not a valid python operator? 1
a) % b) in c) # d) **
3. What will be the output of the following python dictionary operation? 1
data = {'A':2000, 'B':2500, 'C':3000, 'A':4000}
print(data)
a) {'A':2000, 'B':2500, 'C':3000, 'A':4000}
b) {'A':2000, 'B':2500, 'C':3000}
c) {'A':4000, 'B':2500, 'C':3000}
d) It will generate an error.
4. 1
print(True or not True and False)
Choose one option from the following that will be the correct output after
executing the above python expression.
a) False b) True c) or d) not
5. Select the correct output of the following python code: 1
str="My program is program for you"
t = str.partition("program")
print(t)
a) ('My ', 'program', ' is ', 'program', ' for you')
b) ('My ', 'program', ' is program for you')
c) ('My ', ' is program for you')
1|Page
d) ('My ', ' is ', ' for you')
6. Which of the file opening mode will open the file for reading and writing in 1
binary mode.
a) rb b) rb+ c) wb d) a+
7. Which of the following statements is True? 1
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key.
8. Which of the following is not part of a DDL query? 1
a) DROP
b) MODIFY
c) DISTINCT
d) ADD
9. Which of the following operations on a string will generate an error? 1
a) "PYTHON"*2
b) "PYTHON" + "10"
c) "PYTHON" + 10
d) "PYTHON" + "PYTHON"
10 _______________ Keyword is used to obtain unique values in a SELECT query 1
. a) UNIQUE
b) DISTINCT
c) SET
d) HAVING
11 Which of the following python statement will bring the read pointer to 10th 1
. character from the end of a file containing 100 characters, opened for
reading in binary mode.
a) File.seek(10,0)
b) File.seek(-10,2)
c) File.seek(-10,1)
d) File.seek(10,2)
12 Which statement in MySql will display all the tables in a database? 1
. a) SELECT * FROM TABLES;
b) USE TABLES;
c) DESCRIBE TABLES;
d) SHOW TABLES;
13 Which of the following is used to receive emails over Internet? 1
. a) SMTP b) POP c) PPP d) VoIP
2|Page
14 What will be the output of the following python expression? 1
print(2**3**2)
a) 64 b) 256 c) 512 d) 32
15 Which of the following is a valid sql statement? 1
. a) ALTER TABLE student SET rollno INT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
16 Which of the following is not valid cursor function while performing database 1
. operations using python. Here Mycur is the cursor object?
a) Mycur.fetch()
b) Mycur.fetchone()
c) Mycur.fetchmany(n)
d) Mycur.fetchall()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A): A variable declared as global inside a function is visible with 1
. changes made to it outside the function.
Reasoning (A): All variables declared outside are not visible inside a function
till they are redeclared with global keyword.
18 Assertion (A): A binary file in python is used to store collection objects like 1
. lists and dictionaries that can be later retrieved in their original form using
pickle module.
Reasoning (A): A binary files are just like normal text files and can be read
using a text editor like notepad.
SECTION B
19 Sameer has written a python function to compute the reverse of a number. 2
. He has however committed a few errors in his code. Rewrite the code after
removing errors also underline the corrections made.
define reverse(num):
rev = 0
While num > 0:
rem == num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))

3|Page
20 Mention two differences between a Hub and a switch in networking. 2
.
OR
Mention one advantage and one disadvantage of Star Topology.

21 a) What will be the output of the following string operation. 1


. str="PYTHON@LANGUAGE"
print(str[2:12:2])

b) Write the output of the following code. 1


data = [1,2,4,5]
for x in data:
x = x + 10
print(data)
22 Mention two differences between a PRIMARY KEY and a UNIQUE KEY. 2
.
23 a) Expand the following abbreviations: 1
. i) URL ii) TCP

b) What is the use of VoIP? 1


24 Predict the output of the following python code: 2
. def foo(s1,s2):
l1=[]
l2=[]
for x in s1:
l1.append(x)
for x in s2:
l2.append(x)
return l1,l2
a,b=foo("FUN",'DAY')
print(a,b)

OR
Predict the output of the following python code:
data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
if x in d:
d[x]=d[x]+1
else:
d[x]=1
print(d)
4|Page
25 A MySQL table, sales have 10 rows. The following queries were executed on 2
. the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10

SELECT COUNT(discount) FROM sales;


COUNT(discount)
6
Write a statement to explain as to why there is a difference in both the
counts.
OR
What is the difference between a Candidate Key and an Alternate Key
SECTION C
26 a) Consider the following tables Emp and Dept: 1+2
. Relation: Emp
Relation: Dept
empcode ename deptid Salary
deptid dname
1001 TOM 10 10000
10 Physics
1002 BOB 11 8000
11 Chemistry
1003 SID 10 9000
1004 JAY 12 9000 12 Biology

1005 JIM 11 10000

What will be the output of the following statement?


SELECT * FROM Emp NATURAL JOIN Dept WHERE dname='Physics';

b) Write output of the queries (i) to (iv) based on the table Sportsclub
Table Name: Sportsclub
playerid pname sports country rating salary

10001 PELE SOCCER BRAZIL A 50000

10002 FEDERER TENNIS SWEDEN A 20000

10003 VIRAT CRICKET INDIA A 15000

10004 SANIA TENNIS INDIA B 5000

10005 NEERAJ ATHLETICS INDIA A 12000

10006 BOLT ATHLETICS JAMAICA A 8000

5|Page
10007 PAUL SNOOKER USA B 10000

(i) SELECT DISTINCT sports FROM Sportsclub;


(ii) SELECT sports, MAX(salary) FROM Sportsclub GROUP BY sports
HAVING sports<>'SNOOKER';
(iii) SELECT pname, sports, salary FROM Sportsclub WHERE
country='INDIA' ORDER BY salary DESC;
(iv) SELECT SUM(salary) FROM Sportsclub WHERE rating='B';
27 A pre-existing text file data.txt has some words written in it. Write a python 3
. function displaywords() that will print all the words that are having length
greater than 3.
Example:
For the fie content:
A man always wants to strive higher in his life
He wants to be perfect.

The output after executing displayword() will be:


Always wants strive higher life wants perfect

OR

A pre-existing text file info.txt has some text written in it. Write a python
function countvowel() that reads the contents of the file and counts the
occurrence of vowels(A,E,I,O,U) in the file.
28 Based on the given set of tables write answers to the following questions. 3
. Table: flights
flightid model company
10 747 Boeing
12 320 Airbus
15 767 Boeing
Table: Booking
ticketno passenger source destination quantity price Flightid
10001 ARUN BAN DEL 2 7000 10
10002 ORAM BAN KOL 3 7500 12
10003 SUMITA DEL MUM 1 6000 15
10004 ALI MUM KOL 2 5600 12
10005 GAGAN MUM DEL 4 5000 10
a) Write a query to display the passenger, source, model and price for all
bookings whose destination is KOL.
b) Identify the column acting as foreign key and the table name where it
is present in the given example.

6|Page
29 Write a function modilst(L) that accepts a list of numbers as argument and 3
. increases the value of the elements by 10 if the elements are divisible by 5.
Also write a proper call statement for the function.
For example:
If list L contains [3,5,10,12,15]
Then the modilist() should make the list L as [3,15,20,12,25]
30 A dictionary contains the names of some cities and their population in crore. 3
. Write a python function push(stack, data), that accepts an empty list, which
is the stack and data, which is the dictionary and pushes the names of those
countries onto the stack whose population is greater than 25 crores.
For example :
The data is having the contents {'India':140, 'USA':50, 'Russia':25, 'Japan':10}
then the execution of the function push() should push India and USA on the
stack.

OR

A list of numbers is used to populate the contents of a stack using a function


push(stack, data) where stack is an empty list and data is the list of numbers.
The function should push all the numbers that are even to the stack. Also
write the function pop() that removes the top element of the stack on its
each call.

SECTION D
31 Magnolia Infotech wants to set up their computer network in the Bangalore 5
. based campus having four buildings. Each block has a number of computers
that are required to be connected for ease of communication, resource
sharing and data security. You are required to suggest the best answers to
the questions i) to v) keeping in mind the building layout on the campus.

HR
Development

Admin
Logistics

Number of Computers.
Block Number of computers
Development 100
HR 120
Admin 200
Logistics 110

7|Page
Distance Between the various blocks
Block Distance
Development to HR 50m
Development to Admin 75m
Development to Logistics 120m
HR to Admin 110m
HR to Logistics 50m
Admin to Logistics 140m

i) Suggest the most appropriate block to host the Server. Also justify
your choice.
ii) Suggest the device that should should be placed in the Server
building so that they can connect to Internet Service Provider to
avail Internet Services.
iii) Suggest the wired medium and draw the cable block to block layout
to economically connect the various blocks.
iv) Suggest the placement of Switches and Repeaters in the network
with justification.
v) Suggest the high-speed wired communication medium between
Bangalore Campus and Mysore campus to establish a data network.
32 a) Write the output of the following code: 2+3
.
def change(m, n=10):
global x
x+=m
n+=x
m=n+x
print(m,n,x)
x=20
change(10)
change(20)

OR (only in a part)

What will be the output of the following python program?


str = ""
name = "9@Days"
for x in name:
if x in "aeiou":
str+=x.upper()
elif not x.isalnum():
8|Page
str+="**"
elif x.isdigit():
pass
else:
str+=x.lower()
print(str)
b) Sumitra wants to write a program to connect to MySQL database using
python and increase the age of all the students who are studying in class 11
by 2 years.
Since she had little understanding of the coding, she left a few blank spaces
in her code. Now help her to complete the code by suggesting correct coding
for statements 1, 2 and 3.
import ________________ as myc # Statement 1
con = myc.connect(host="locahost", user="root", passwd="",
database="mydb")
mycursor = __________________ #Statement 2
sql = "UPDATE student SET age=age+2 WHERE class='XI'"
mycursor.execute(sql)
sql = "SELECT * FROM student"
mycursor=con.execute(sql)
result = _____________________ #Statement 3
for row in result:
print(row)

Statement 1 : The required module to be imported


Statement 2: To initialize the cursor object.
Statement 3: To read all the rows from the cursor object

33 A binary file data.dat needs to be created with following data written it in the 2+3
. form of Dictionaries.
Rollno Name Age
1001 TOM 17
1002 BOB 16
1003 KAY 16
Write the following functions in python accommodate the data and
manipulate it.
a) A function insert() that creates the data.dat file in your system and
writes the three dictionaries.
b) A function() read() that reads the data from the binary file and displays
the dictionaries whose age is 16.

9|Page
34 Tarun created the following table in MySQL to maintain stock for the items 1+1+
. he has. 2

Table : Inventory
Productid pname company stock price rating

10001 Biscuit Parley 1000 15 C

10002 Toffee Parley 500 5 B

10003 Eclairs Cadbury 800 10 A

10004 Cold Drink Coca Cola 500 25 NULL

1005 Biscuit Britania 500 30 NULL

1006 Chocolate Cadbury 700 50 C


Based on the above table answer the following questions.

a) Identify the primary key in the table with valid justification.


b) What is the degree and cardinality of the given table.
c) Write a query to increase the stock for all products whose company is
Parley.
OR (only for part c)
Write a query to delete all the rows from the table which are not
having any rating.
35 Sudheer has written a program to read and write using a csv file. He has
. written the following code but failed to write completely, leaving some
blanks. Help him to complete the program by writing the missing lines by
following the questions a) to d)

_________________ #Statement 1
headings = ['Country','Capital','Population']
data = [['India', 'Delhi',130],['USA','Washington DC',50],[Japan,Tokyo,2]]
f = open('country.csv','w', newline="")
csvwriter = csv.writer(f)
csvwriter.writerow(headings)
________________ #Statement 2
f.close()
f = open('country.csv','r')
csvreader = csv.reader(f)
head = _________________ #Statement 3
print(head)
for x in __________: #Statement 4
if int(x[2])>50:
print(x)
10 | P a g e
a) Statement 1 – Write the python statement that will allow Sudheer
work with csv files.
b) Statement 2 – Write a python statement that will write the list
containing the data available as a nested list in the csv file
c) Statement 3 – Write a python statement to read the header row in to
the head object.
d) Statement 4 – Write the object that contains the data that has been
read from the file.

****End****

11 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
BENGALURU REGION
FIRST PRE-BOARD EXAM (SESSION 2022-23)

CLASS: XII MAX MARKS:70


SUBJECT: COMPUTER SCIENCE TIME: 3 HOURS
MARKING SCHEME
SECTION A
1. State True or False 1
“Python has a set of keywords that can also be used to declare variables”
A False
2. Which of the following is not a valid python operator? 1
a) % b) in c) # d) **
A #
3. What will be the output of the following python dictionary operation? 1
data = {'A':2000, 'B':2500, 'C':3000, 'A':4000}
print(data)
a) {'A':2000, 'B':2500, 'C':3000, 'A':4000}
b) {'A':2000, 'B':2500, 'C':3000}
c) {'A':4000, 'B':2500, 'C':3000}
d) It will generate an error.
A {'A':4000, 'B':2500, 'C':3000}
4. 1
print(True or not True and False)
Choose one option from the following that will be the correct output after
executing the above python expression.
a) False b) True c) or d) not
A True
5. Select the correct output of the following python code: 1
str="My program is program for you"
t = str.partition("program")
print(t)
a) ('My ', 'program', ' is ', 'program', ' for you')
b) ('My ', 'program', ' is program for you')
c) ('My ', ' is program for you')
d) ('My ', ' is ', ' for you')
A a) ('My ', 'program', ' is program for you')

1|Page
6. Which of the file opening mode will open the file for reading and writing in 1
binary mode.
a) rb b) rb+ c) wb d) a+
A rb+
7. Which of the following statements is True? 1
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key.
A There can be only one Primary Key in a Table
8. Which of the following is not part of a DDL query? 1
a) DROP
b) MODIFY
c) DISTINCT
d) ADD
A DISTINCT
9. Which of the following operations on a string will generate an error? 1
a) "PYTHON"*2
b) "PYTHON" + "10"
c) "PYTHON" + 10
d) "PYTHON" + "PYTHON"
A "PYTHON" + 10
10. _______________ Keyword is used to obtain unique values in a SELECT 1
query
a) UNIQUE
b) DISTINCT
c) SET
d) HAVING
A DISTINCT
11. Which of the following python statement will bring the read pointer to 10th 1
character from the end of a file containing 100 characters, opened for
reading in binary mode.
a) File.seek(10,0)
b) File.seek(-10,2)
c) File.seek(-10,1)
d) File.seek(10,2)
A File.seek(-10,2)

2|Page
12. Which statement in MySql will display all the tables in a database? 1
a) SELECT * FROM TABLES;
b) USE TABLES;
c) DESCRIBE TABLES;
d) SHOW TABLES;
A SHOW TABLES;
13. Which of the following is used to receive emails over Internet? 1
a) SMTP b) POP3 c) PPP d) VoIP
A POP3
14 What will be the output of the following python expression? 1
print(2**3**2)
a) 64 b) 256 c) 512 d) 32
A 512
15. Which of the following is a valid sql statement? 1
a) ALTER TABLE student SET rollno INT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
A DELETE FROM student;
16. Which of the following is not valid cursor function while performing database 1
operations using python. Here Mycur is the cursor object?
a) Mycur.fetch()
b) Mycur.fetchone()
c) Mycur.fetchmany(n)
d) Mycur.fetchall()
A Mycur.fetch()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17. Assertion (A): A variable declared as global inside a function is visible with 1
changes made to it outside the function.
Reasoning (A): All variables declared outside are not visible inside a function
till they are redeclared with global keyword.
A Both A and R are true and R is the correct explanation for A

3|Page
18. Assertion (A): A binary file in python is used to store collection objects like 1
lists and dictionaries that can be later retrieved in their original form using
pickle module.
Reasoning (A): A binary files are just like normal text files and can be read
using a text editor like notepad.
A A is True and R is False
SECTION B
19. Sameer has written a python function to compute the reverse of a number. 2
He has however committed a few errors in his code. Rewrite the code after
removing errors also underline the corrections made.
define reverse(num):
rev = 0
While num > 0:
rem == num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))
A def reverse(num):
rev = 0
while num > 0:
rem = num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))
20. Mention two differences between a Hub and a switch in networking. 2
OR
Mention one advantage and one disadvantage of Star Topology.

A Hub Switch
Hub is a passive Device Switch is an active device
Hub broadcasts messages to all Switch sends the messages to
nodes intended node.
Or any other valid difference between the two. Each difference carries 1
mark.
OR

Advantage: The network remains operational even if one of the nodes stops
working.
Disadvantage: The network stops working if the central hub stops working.
Or any other valid advantage or disadvantage. Each carries 1 mark
4|Page
21. a) What will be the output of the following string operation. 1
str="PYTHON@LANGUAGE"
print(str[2:12:2])

b) Write the output of the following code. 1


data = [1,2,4,5]
for x in data:
x = x + 10
print(data)
A TO@AG - No partial marking
[1,2,4,5] - No partial marking
22 Mention two differences between a PRIMARY KEY and a UNIQUE KEY 2
A PRIMARY KEY UNIQUE KEY
There can be only one primary key in a There can be more than one unique keys
table in a table
The primary key cannot have null values Unique can have null values
Each difference carries 1 mark.
23. a) Expand the following abbreviations: 1
i) URL ii) TCP

b) What is the use of VoIP? 1


A i) Uniform Resource Locator - 1/2
ii) Transmission Control Protocol - ½

VoIP is used to transfer audio and video over internet - 1


24. Predict the output of the following python code: 2
def foo(s1,s2):
l1=[]
l2=[]
for x in s1:
l1.append(x)
for x in s2:
l2.append(x)
return l1,l2
a,b=foo("FUN",'DAY')
print(a,b)

OR
Predict the output of the following python code:
data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
5|Page
if x in d:
d[x]=d[x]+1
else:
d[x]=1
print(d)
A ['F', 'U', 'N'] ['D', 'A', 'Y'] Each list correctly written will fetch 1 mark. ½ mark
can be given if the list is figured out in the answer.
OR
{2: 3, 4: 3, 1: 2, 3: 2}
The dictionary elements can be written in any order.
25. A MySQL table, sales have 10 rows. The following queries were executed on 2
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10

SELECT COUNT(discount) FROM sales;


COUNT(discount)
6
Write a statement to explain as to why there is a difference in both the
counts.
OR
What is the difference between a Candidate Key and an Alternate Key
A The values are different because discount column is having 4 rows with NULL
values.

OR

CANDIDATE KEY ALTERNATE KEY


All the attributes in a relation that All the leftover candidate keys after
have the potential to become a selecting the primary key
Primary key
SECTION C
26. a) Consider the following tables Emp and Dept: 1+2

6|Page
Relation: Emp
Relation: Dept
empcode ename deptid Salary
deptid dname
1001 TOM 10 10000
10 Physics
1002 BOB 11 8000
11 Chemistry
1003 SID 10 9000

1004 JAY 12 9000 12 Biology

What will be the output of the


following statement?
SELECT * FROM Emp NATURAL JOIN Dept WHERE dname='Physics';

b) Write output of the queries (i) to (iv) based on the table Sportsclub
Table Name: Sportsclub
playerid pname sports country rating salary

10001 PELE SOCCER BRAZIL A 50000

10002 FEDERER TENNIS SWEDEN A 20000

10003 VIRAT CRICKET INDIA A 15000

10004 SANIA TENNIS INDIA B 5000

10005 NEERAJ ATHLETICS INDIA A 12000

10006 BOLT ATHLETICS JAMAICA A 8000

10007 PAUL SNOOKER USA B 10000


(i) SELECT DISTINCT sports FROM Sportsclub;
(ii) SELECT sports, MAX(salary) FROM Sportsclub GROUP BY sports
HAVING sports<>'SNOOKER';
(iii) SELECT pname, sports, salary FROM Sportsclub WHERE
country='INDIA' ORDER BY salary DESC;
(iv) SELECT SUM(salary) FROM Sportsclub WHERE rating='B';
A a)
deptid empcode ename Salary dname
10 1001 TOM 10000 Physics
10 1003 SID 9000 Physics

7|Page
i) DISTINCT sports
SOCCER
TENNIS
CRICKET
ATHLETICS
SNOOKER
ii)

Sports MAX(salary)
SOCCER 50000
TENNIS 20000
CRICKET 15000
ATHLETICS 12000
iii)
pname sports salary
VIRAT CRICKET 15000
NEERAJ ATHLETICS 12000
SANIA TENNIS 5000
iv)
SUM(salary)
15000
27. A pre-existing text file data.txt has some words written in it. Write a python 3
function displaywords() that will print all the words that are having length
greater than 3.
Example:
For the fie content:
A man always wants to strive higher in his life
He wants to be perfect.

The output after executing displayword() will be:


Always wants strive higher life wants perfect

OR

A pre-existing text file info.txt has some text written in it. Write a python
function countvowel() that reads the contents of the file and counts the
occurrence of vowels(A,E,I,O,U) in the file.

8|Page
A def displaywords():
f = open('data.txt','r')
s = f.read()
lst = s.split()
for x in lst:
if len(x)>3:
print(x, end=" ")
f.close()

OR

def countvowels():
f - open('info.txt', 'r')
s = f.read()
count = 0
for x in s:
if x in 'AEIOU':
count+=1
print(count)
f.close()

Correct definition of function will fetch 3 marks. For each syntax error ½
mark may be deducted. No marks to be deducted for using a different logic.
28. Based on the given set of tables write answers to the following questions. 3
Table: flights
flightid model company
10 747 Boeing
12 320 Airbus
15 767 Boeing
Table: Booking
ticketno passenger source destination quantity price Flightid
10001 ARUN BAN DEL 2 7000 10
10002 ORAM BAN KOL 3 7500 12
10003 SUMITA DEL MUM 1 6000 15
10004 ALI MUM KOL 2 5600 12
10005 GAGAN MUM DEL 4 5000 10
a) Write a query to display the passenger, source, model and price for all
bookings whose destination is KOL.
b) Identify the column acting as foreign key and the table name where it
is present in the given example.

9|Page
A a) SELECT passenger, source, model, price FROM booking, flights WHERE
bookings.flightid = flights.flightid AND destination='KOL';

2 marks for correct answer. ½ mark to be deducted for each error.

b) Flighted in the bookings table is the foreign key. (1 mark)


29. Write a function modilst(L) that accepts a list of numbers as argument and 3
increases the value of the elements by 10 if the elements are divisible by 5.
Also write a proper call statement for the function.
For example:
If list L contains [3,5,10,12,15]
Then the modilist() should make the list L as [3,15,20,12,25]
A def modilst(L):
for i in range(len(L)):
if L[i] % 5 == 0:
L[i]+=10

L = [12,10,15,20,25]
modilst(L)
print(L)

½ mark to deducted for each syntax error. Marks to be awarded for a


different logic. 1 mark to be deducted if the function call is not written
30. A dictionary contains the names of some cities and their population in crore. 3
Write a python function push(stack, data), that accepts an empty list, which
is the stack and data, which is the dictionary and pushes the names of those
countries onto the stack whose population is greater than 25 crores.
For example :
The data is having the contents {'India':140, 'USA':50, 'Russia':25, 'Japan':10}
then the execution of the function push() should push India and USA on the
stack.

OR

A list of numbers is used to populate the contents of a stack using a function


push(stack, data) where stack is an empty list and data is the list of numbers.
The function should push all the numbers that are even to the stack. Also
write the function pop(stack) that removes the top element of the stack on
its each call. Also write the function calls.

10 | P a g e
A data={'India':140, 'USA':50, 'Russia':25, 'Japan':10}
stack=[]
def push(stack, data):
for x in data:
if data[x]>25:
stack.append(x)
push(stack, data)
print(stack)

½ mark should be deducted for all incorrect syntax. Full marks to be


awarded for any other logic that produces the correct result.

OR

data = [1,2,3,4,5,6,7,8]
stack = []
def push(stack, data):
for x in data:
if x % 2 == 0:
stack.append(x)
def pop(stack):
if len(stack)==0:
return "stack empty"
else:
return stack.pop()

push(stack, data)
print(pop(stack))

½ mark should be deducted for all incorrect syntax. Full marks to be


awarded for any other logic that produces the correct result.

SECTION D
31 Magnolia Infotech wants to set up their computer network in the Bangalore 5
. based campus having four buildings. Each block has a number of computers
that are required to be connected for ease of communication, resource
sharing and data security. You are required to suggest the best answers to
the questions i) to v) keeping in mind the building layout on the campus.

11 | P a g e
HR
Development

Admin
Logistics

Number of Computers.
Block Number of computers
Development 100
HR 120
Admin 200
Logistics 110

Distance Between the various blocks


Block Distance
Development to HR 50m
Development to Admin 75m
Development to Logistics 120m
HR to Admin 110m
HR to Logistics 50m
Admin to Logistics 140m

i) Suggest the most appropriate block to host the Server. Also justify
your choice.
ii) Suggest the device that should should be placed in the Server
building so that they can connect to Internet Service Provider to
avail Internet Services.
iii) Suggest the wired medium and draw the cable block to block layout
to economically connect the various blocks.
iv) Suggest the placement of Switches and Repeaters in the network
with justification.
v) Suggest the high-speed wired communication medium between
Bangalore Campus and Mysore campus to establish a data network.
A i) Admin Block since it has maximum number of computers.
ii) Modem should be placed in the Server building
iii) The wired medium is UTP/STP cables.

Development HR

Admin
Logistics

12 | P a g e
iv) Switches in all the blocks since the computers need to be
connected to the network. Repeaters between Admin and HR block
& Admin and Logistics block. The reason being the distance is more
than 100m.
v) Optical Fiber cable connection.

32 a) Write the output of the following code: 2+3


.
def change(m, n=10):
global x
x+=m
n+=x
m=n+x
print(m,n,x)
x=20
change(10)
change(20)

OR (only in a part)

What will be the output of the following python program?


str = ""
name = "9@Days"
for x in name:
if x in "aeiou":
str+=x.upper()
elif not x.isalnum():
str+="**"
elif x.isdigit():
pass
else:
str+=x.lower()
print(str)
b) Sumitra wants to write a program to connect to MySQL database using
python and increase the age of all the students who are studying in class 11
by 2 years.
Since she had little understanding of the coding, she left a few blank spaces
in her code. Now help her to complete the code by suggesting correct coding
for statements 1, 2 and 3.

13 | P a g e
import ________________ as myc # Statement 1
con = myc.connect(host="locahost", user="root", passwd="",
database="mydb")
mycursor = __________________ #Statement 2
sql = "UPDATE student SET age=age+2 WHERE class='XI'"
mycursor.execute(sql)
sql = "SELECT * FROM student"
mycursor=con.execute(sql)
result = _____________________ #Statement 3
for row in result:
print(row)

Statement 1 : The required module to be imported


Statement 2: To initialize the cursor object.
Statement 3: To read all the rows from the cursor object

A a) 70 40 30
110 60 50
1 mark for each correct row of answer. Partial marks to be given if
partial correct answers are there.

OR

**dAys
2 marks for correct answer. Partial marks may be given for partially
correct answer.
b) mysql.connector
c) con.cursor()
d) mycursor.fetchall()

1 mark for each correct answer


33 A binary file data.dat needs to be created with following data written it in the 2+3
. form of Dictionaries.
Rollno Name Age
1001 TOM 17
1002 BOB 16
1003 KAY 16
Write the following functions in python accommodate the data and
manipulate it.
a) A function insert() that creates the data.dat file in your system and
writes the three dictionaries.

14 | P a g e
b) A function read() that reads the data from the binary file and displays
the dictionaries whose age is 16.

A import pickle
def insert():
d1 = {'Rollno':1001, 'Name':'TOM', 'Age':17}
d2 = {'Rollno':1002, 'Name':'BOB', 'Age':16}
d3 = {'Rollno':1003, 'Name':'KAY', 'Age':16}
f = open("data.dat","wb")
pickle.dump(d1,f)
pickle.dump(d2,f)
pickle.dump(d3,f)
f.close()

def read():
f = open("data.dat", "rb")
while True:
try:
d = pickle.load(f)
if d['Age']==16:
print(d)
except EOFError:
break
f.close()

The insert() function has 2 marks. Deduct ½ mark for each syntax error
The read() function carries 3 marks. Deduct ½ marks for each syntax error
34 Tarun created the following table in MySQL to maintain stock for the items 1+1+
. he has. 2

Table : Inventory
Productid pname company stock price rating

10001 Biscuit Parley 1000 15 C

10002 Toffee Parley 500 5 B

10003 Eclairs Cadbury 800 10 A

10004 Cold Drink Coca Cola 500 25 NULL

10005 Biscuit Britania 500 30 NULL

10006 Chocolate Cadbury 700 50 C


Based on the above table answer the following questions.

15 | P a g e
a) Identify the primary key in the table with valid justification.
b) What is the degree and cardinality of the given table.
c) Write a query to increase the stock for all products by 20 whose
company is Parley.
OR (only for part c)
Write a query to delete all the rows from the table which are not
having any rating.
A a) The Primary Key should be Productid since it uniquely identifies each
row. (1)
b) Degree – 6 Cardinality – 6 (½ + ½)
c) UPDATE inventory SET stock=stock+10 WHERE company = 'Parley';
OR
DELETE FROM inventory WHERE RATING IS NULL; (2)
35 Sudheer has written a program to read and write using a csv file. He has
. written the following code but failed to write completely, leaving some
blanks. Help him to complete the program by writing the missing lines by
following the questions a) to d)

_________________ #Statement 1
headings = ['Country','Capital','Population']
data = [['India', 'Delhi',130],['USA','Washington DC',50],[Japan,Tokyo,2]]
f = open('country.csv','w', newline="")
csvwriter = csv.writer(f)
csvwriter.writerow(headings)
________________ #Statement 2
f.close()
f = open('country.csv','r')
csvreader = csv.reader(f)
head = _________________ #Statement 3
print(head)
for x in __________: #Statement 4
if int(x[2])>50:
print(x)

a) Statement 1 – Write the python statement that will allow Sudheer


work with csv files.
b) Statement 2 – Write a python statement that will write the list
containing the data available as a nested list in the csv file
c) Statement 3 – Write a python statement to read the header row in to
the head object.
d) Statement 4 – Write the object that contains the data that has been
read from the file.

16 | P a g e
A a) import csv
b) csvwriter.writerows(data)
c) next(csvreader)
d) csvreader
1 mark for each correct answer.

****End****

17 | P a g e
KENDRIYA VIDYALAYA SANGATHAN, CHANDIGARH REGION 2022-23
PREBOARD-I
CLASS – XII COMPUTER SCIENCE (083)
TIME ALLOWED: 03 HOURS M.M.: 70
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1. Fill in the Blank 1
The explicit conversion of an operand to a specific type is called _____
(a)Type casting (b) coercion (c) translation (d) None of these
2. Which of the following is not a core data type in Python? 1
(a)Lists (b) Dictionaries (c)Tuple (d) Class
3. What will the following code do? 1
dict={"Exam":"AISSCE", "Year":2022}
dict.update({"Year”:2023} )

a. It will create new dictionary dict={” Year”:2023}and old dictionary


will be deleted
b. It will throw an error and dictionary cannot updated
c. It will make the content of dictionary as dict={"Exam":"AISSCE",
"Year":2023}
d. It will throw an error and dictionary and do nothing
4. What will be the value of the expression :14+13%15 1
5 Select the correct output of the code: 1
a= "Year 2022 at All the best" a = a.split('2')
a = a[0] + ". " + a[1] + ". " + a[3] print (b)
(a) Year . 0. at All the best (b) Year 0. at All the best
(c) Year . 022. at All the best (d) Year . 0. at all the best

6. Which of the following mode will refer to binary data? 1


(a)r (b) w (c) + (d) b
7. Fill in the blank: 1
______ command is used to remove a column from a table in SQL.
(a) update (b)remove (c) alter (d)drop
8. Which of the following commands will delete the rows of table? 1
(a) DELETE command (b) DROP Command
(c) REMOVE Command (d) ALTER Command
9. Which of the following statement(s) would give an error after executing the following code? 1
S="Welcome to class XII" # Statement 1print(S) #
Statement 2 S="Thank you" # Statement 3
S[0]= '@' # Statement 4
S=S+"Thank you" # Statement 5

(a) Statement 3 (b) Statement 4


(b) Statement 5 (d) Statement 4 and 5
10. Logical Operators used in SQL are? 1
(a) AND,OR,NOT (b) &&,||,!
(c) $,|,! (d) None of these

1
11 The correct syntax of seek() is:
(a) file_object.seek(offset [, reference_point]) (b) seek(offset [,
reference_point])
(c) seek(offset, file_object) (d)
seek.file_object(offset)
12. Fill in the blank: 1
All tuples in the relation are assigned NULL as the value for the new Attribute,with the ________
Command
(a) MODIFY (b) TAILOR (c)ELIMINATE (d) ALTER
13. What is the size of IPv4 address? 1
(a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes
14. What will be the output of the following expression? 1
24//6%3 , 24//4//2 , 48//3//4
a)(1,3,4) b)(0,3,4) c)(1,12,Error) d)(1,3,#error)
15. Which of the following ignores the NULL values inSQL? 1
a) Count(*) b) count() c)total(*) d)None of these
16. Which of the following is not a legal method for fetching records from a database from within a 1
Python program?
(a) fetchone() b)fetchtwo() (c) fetchall() (d) fetchmany()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False (d) A is false but R is True
17. Assertion (A):- If the arguments in a function call statement match the number and order of 1
arguments as defined in the function definition, such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s)
followed by positional argument(s).
18. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a 1
text file.
Reason (R): The information is organized with one record on each line and each field is separated
by comma.
SECTION B
19. Preety has written a code to add two numbers .Her code is having errors. Rewrite the correct 2
code and underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
20. Write two points of difference between Hub and Switch. 2
OR
Write two points of difference between Web PageL and Web site.
21. Write the output of following code and explain the difference between a*3 and (a,a,a) 2
a=(1,2,3)
print(a*3)
print(a,a,a)
22 Differentiate between DDL and DML with one Example each. 2
23 (a) Write the full forms of the following: 2
(i) SMTP (ii) PPP
(b) What is the use of TELNET?
24 What do you understand the default argument in function? Which function parameter must be given default 2
argument if it is used? Give example of function header to illustrate default argument
OR
Ravi a python programmer is working on a project, for some requirement, he has to define a function with
name CalculateInterest(), he defined it as:
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above function and what is the
solution.

2
25 Write the output of the queries (a) to (d) based on the table 2

(a) SELECT min(Population) FROM country;


(b) SELECT max(SurfaceArea) FROM country Where Lifeexpectancy <50;
(c) SELECT avg(LifeExpectancy) FROM country Where CName Like "%G%";
(d) SELECT Count(Distinct Continent) FROM country;
OR
(a) Identify the candidate key(s) from the table Country.
(b) Consider the table CAPITAL given below:

Which field will be considered as the foreign key if the tables


COUNTRY and CAPITAL are related in a database?
SECTION-C
26 Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting given below: 3
Table: Stationary
S_ID StationaryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
1. SELECT count(DISTINCT Address) FROM Consumer;
2. 2. SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary
GROUP BY Company;
SELECT Consumer.ConsumerName, Stationary.StationaryName, Stationary.Price FROM Stationary,
Consumer WHERE Consumer.S_ID = Stationary.S_ID;
27. Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT” and count the 3
number of times “AND” occurs in the file. (include AND/and/And in the counting)
OR
Write a function DISPLAYWORDS( ) in python to display the count of words starting with “t” or “T”
in a text file ‘STORY.TXT’.
28 (Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given 3
below:

3
SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE
DESIGNATION = ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
29. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the 3
function. The function returns another list named ‘indexList’ that stores the indices of all Non-
Zero Elements of L.
For example:
If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
30. Write a program to perform push operations on a Stack containing Student details as given in the 3
following definition of student node:
RNo integer
Name String
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_push(stk, item):
# Write the code to push student details using stack.
OR
Write a program to perform pop operations on a Stack containing Student details as given in the
following definition of student node:
RNo integer
Name String
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_pop(stk):
# Write the code to pop a student using stack

4
SECTION D
31. MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training
centres in various cities in next 2 years. Their first campus is coming up in Kashipur district. At
Kashipur campus, they are planning to have 3 different blocks for App development, Web
designing and Movie editing. Each block has number of computers, which are required to be
connected in a network for communication, data and resource sharing. As a network consultant
of this company, you have to suggest the best network related solutions for them for
issues/problems raised in question nos. (i) to (v), keeping in mind the distances between various
Distance between various blocks/locations:
blocks/locations and other given parameters.
APP
KASHIPUR
DEVELOPM CAMPUS MOVIE
ENT EDITING
MUSSOORIE
CAMPUS
WEB
DESIGNING

Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 km
Number of computers
Block Number of Computers
App development 75
Web designing 50
Movie editing 80
(i) Suggest the most appropriate block/location to house the SERVER in the Kashipur campus
(out of the 3 blocks) to get the best and effective connectivity. Justify your answer. 1
1
(ii) Suggest a device/software to be installed in the Kashipur Campus to take care of data
1
security.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to economically
connect various blocks within the Kashipur Campus.
1
(iv) Suggest the placement of the following devices with appropriate reasons:
aSwitch / Hub
b Repeater 1
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between
Kashipur Campus and Mussoorie Campus.

5
32. (a) What will be the output of following program: 2+3
s="welcome2kv"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)

(b)The code given below reads the following record from the table named studentand
displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is tiger
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose marks are
greater than 75.
Statement 3- to read the complete result of the query (records whose
marks are greater than 75) into the object named data, from the table student in the
database.
import mysql.connector as mysql def sql_data():
con1=mysql.connect(host="localhost",user="root", password="tiger",
database="school")
mycursor=_______________ #Statement 1 print("Students
with marks greater than 75 are :
")
_________________________ #Statement 2
data=__________________ #Statement 3 for i in data:
print(i)
print()
33. What is the advantage of using a csv file for permanent storage? Write a Program in Python that 5
defines and calls the following user defined functions:

(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record
consists of a list with field elements as empid, name and mobile to store employee id,
employee name and employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
OR

Give any one point of difference between a binary file and a csv file. Write a Program in Python
that defines and calls the following user defined functions:

(i) add() – To accept and add data of an employee to a CSV


file ‘furdata.csv’. Each record consists of a list with field elements as fid, fname and fprice
to store furniture id, furniture name and furniture price respectively.
(ii) search()- To display the records of the furniture whose price is more than 10000.
SECTION E
6
34 Write SQL commands for the following queries (i) to (v) based on the relation 4

Trainer and Course given below:


(i) Display the Trainer Name, City & Salary in descending order of
their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute
in the month of December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from
tables TRAINER and COURSE of all those courses whose FEES
is less than or equal to 10000.
(iv) To display number of Trainers from each city.
OR
(iv) To display the Trainer ID and Name of the trainer who are not
belongs to ‘Mumbai’ and ‘DELHI’

35. Anuj Kumar of class 12 is writing a program to create a CSV file “user.csv”
which will contain user name and password for some entries. He has written thefollowing code. As
a programmer, help him to successfully execute the giventask.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file 4
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)

(a) Name the module he should import in Line 1.


(b) In which mode, Anuj should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.

*************************************** End of the Paper ***************************************

7
KENDRIYA VIDYALAYA SANGATHAN,
CHENNAI REGION
PRE-BOARD EXAM 2022-23
Class:X
Time: 3 hrs
Computer Science- (083) Max Marks: 70

General Instructions:
1. This
question paper contains five sections,Section A to E.
2. All
questions are compulsory.
3. SectionAhave18questionscarrying0I markeach.
4. SectionBhas07VeryShortAnswertypequestionscarrying02markseach.
5. SectionChas05ShortAnswertypequestionscarrying03markseach.

SectionDhas03LongAnswertypequestionscarrying05 markseach.
7. SectionEhas02questionscarrying04markseach.Oneinternalchoicei

sgivenin Q34against part c only.


8.
All programming questions are to be answered using Python Language
only.
1. State True or False: SECTION A
"A
dictionary key must be of a data type that is mutable."
2. What will be the data type of d, if d=(15) ?
a) int (b) tuple (c) list (d) string
3. Which of the following is a valid identifier in Python:
(aelse if (b) for cpass (d) 2count
4. Consider the given expression:
not 5 or 4 and 10 and 'bye'
Which of the following will be correct output if the given expression is
evaluated?
(a)True (b) False (c)10 ay bye
5. Select the corect output of the code:
for i in "QUITE":
print([i.lower0], end-"#")

(a qhuitthe#{b) ['quitet#"]
T#Tu]#[TJ#Tr]#Te]H() F'quite'] #
6. Which file mode can be used to open a binary file in both append and read
mode?
a) w+ b) wb+ ab+ d)'at
7. Fill in the blank:
TheSQL built-in function calculates the average of values in
numeric colurans.
(anumerichAVGO (c) AVERAGEO (d) COUNTO
[Which of the following commands will be used to select a particular database
named "Student" from MYSQL Database?
(a) SELECTStudent;
(b) DESCRIBE Student:
c USE Student;
CONNECT Student;
Which of the folloWIng Statement(s) would give an error after executing the
9.
following code?

d ("A":1, "B": 2, "C:3, "D":4) #statement 1


sum_keys =0 #statement 2
for val in d.keys): #statement 3
val #statement 4
Sum keys Sum_keys+
print(sum keys)
(a) Statement 1 b) Statement 2
(c) Statements (d) Statement4
10. Fill inthe blank:
key in any other
An attribute in a relation is a
foreign key ifit is the
relation.
(a) Candidate Key (b) Foreign Key
O Primary Key (d)Unique Key_
11. Which option correctly explains tell) method?

Ma) tells the current position within the file.


(b) tells the name of file.
()moves the file position to a different location.
current

(d) it changes the file position only if allowed to do so else returns an error.
12. Fill in the blank:
When two conditions must both be true for the rows to be selected, the
conditions are separated bythe SQL keyword
(a)ALL (bIN AND (d)OR
13.Fill in the blank: line interface on a remote
protocol provides access to command
computer.
(a) FIP (6) PPP )Telnet (d) SMTTP
in Python?
14. What will the following expression be evaluated to
print(25 //4 +3**1**2* 2)
(a)24 (b) 18 c)6 12 table is
definition of a
15. Which statement in SQL allows to change the
2
(a) ALTER (6) UPDATE(¢) CREATE(d) SELECT
16. The statement which is used to get the number ofrows
fetched by execute)

method of cursor:
(a) cursor.rowcount (b) cursor.rowscount()
(c) cursor.allrows0 (d) cursor.countrowsO

Q17and18areASSERTIONANDREASONINGbasedquestions.Markthecorrect
choice as
(a) Both Aand R are true and R Is the correct explanation forA
(b) Both A and R are true and R 1S not the correct
explanation for A
Ris False
(c) A isTrue but
but R
A is false is True
(d)
exits function.
Assertion(A):- In Python, statement return [expression]
a
17.

Return statement passes back an expression


to the caller. A|
Reasoning(R):-
None.
return statement with no arguments is the'same as return

in
| 18. Assertion(A):CSV module allows to
write a single record into each row
CSV file using write row) function.
Reason(R):The write row) function creates headerrow in csv file
by default.
SECTION B
2
code in python after removing all the syntax errors.
19. Rewrite the following
Underline each corection done in the code.

num1,num2 10
While num1 % num2 = 0
num1+=20
num2t=30
Else:
print('hello')
2
20. Write two advantages and two disadvantages of circuit switching.

OR

Differentiate between Web server and web browser. Write any two popular
web brovwsers.

Write two points of difference between ALTER and UPDATE command


in 2
21.
SQL.
22. (a) Given is a Python
List declaration: 2
Ist1=3945,23,15,25, 601
(2 Oc

3
What will be the output of
print(Ist1.index(23)) 2

(b) Write the output ot the code given below:


x=["rahul",5, B",20,30]
x.insert(1,3)
x.insert(3, "akon)
print(x[2)D

23. (a)Write the full forms ithe following:


(6) FTP (ii) HTTPS

b)Name the protocolswhich are used for sending andreceiving emails?


rython
2
24. Predict the output of the code given below:
st= "python programming"
count=4
while True:
ifst[o"p":
st st[2:]
elifst[-2]="n":
st st[:4]
else:
countt=1

break
print(st)
print(count)
OR
below:
Predict the output of the Python code given

myvalue=["A", 40, "B", 60, "C", 20]


alpha =0
beta = ""

gama = 0

for i in range(1,6,2):
alpha+i
beta +myvaluefi-1]+ "#"
gama + myvalue[i]

print(alpha, beta, gama) PRIMARY KEY and UNIQUE KEY of |2


25. What do you understand by theterms
a relation in relational database?
OR
28
Categorize the following commands as DDLorDML: DROP, DELETE,

SELECT, ALTER
SECTIONC
26. T(a)Consider the following
tables- Applicants and Centre 1+2

Table: Applicants
Appno Name Subject
C01 Mohan English

CO2 Raju Hindi

Table: Centre
Appno City
C02 Madurai

C03 Chennai
C02 Jaipur

What will be the output of the following statement?


SELECT* FROM Applicants NATURAL JOIN Centre

Write the output ofthe queries (i)


to (iv) based on the table, Car given
(b)
below:
CCODECNAME MAKE COLOUR CAPACITY CHARGES |
White 7 | 1500_
105 Fortuner |Toyota 1000
Nexon|Tata Black 5
245 2000
130 Duster Renault Green
2500
225 Kwid Renault Grey
4000
|12 Baleno_ |Suzuki_Red 3500
207 Nano Tata Blue
FROM CAR;
) SELECT DISTINCT MAKE
FROM CAR GROUPBY MAKE
(i) SELECT MAKE, COUNT(*)
CAPACITY>5 ORDER
CNAME FROM CAR WHERE
(iii)SELECT
BY CNAME;
FROM CAR WHERE
SELECT CNAME, MAKE
(iv)
CHARGES>2500; and 3
to read lines from atext file 'visiors.bct',
Write function Phyton
in
27. a
which are starting with an alphabet
'P".
display only those lines,
is:
If the content offile
2 Csc
various cities
tics are
Visitors from coming here.
Particularly, they war to visit the museum.
Looking to learn more story about countries with their cultures.

The output should be:


Particularly, they want to visit the museum.

OR
Write a method in Python to read lines from a text file 'book.txt', to find and
or the word
display the occurrence 'are'. For example, if the content of the
is:

Books are referred to as a man's best friend. They are very beneficial for
mankind and have helped it evolve. Books leave a deep impact on us and are

responsible for upliftingour mood.

|The output should be 3._


28. (a)Consider the following tables EMPLOYEE and SALARY. 3

Table: EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
Akash |Executive| S03 |2003-03-231980-01-13
101
|ManagerS02 2010-02-121987-07-22
102 Rajiv
103 Jonny RO S03 2009-06-24 1983-02-24
104 Naziya GM S02 2006-08-11 1984-03-03
S01 2004-12-29 1982-01-19
105 | Pritam CEO

Table: SAL
SGRADE SALARY HRA
S01 56000 18000
32000 12000
S02
S03 24000 8000

Give the output of the following SQL queries:


GROUP BY
COUNT(SGRADE), SGRADE FROM EMPLOYEE
() SELECT
SGRADE;
FROM EMPLOYEE;
(ii) SELECT MIN(DOB), MAX(DO) EMPLOYEE E, SALS WHERE
(ii) SELECT NAME, SALARY FROM
E.SGRADE-S.SGRADE ANDE.ECODE<103;
WHERE SGRADE
SELECT SGRADE, SALARY+HRA FROM SAL
(iv)
S02
in a database.
command to view structure oftable FOOD
(6)Write the
list Numlist 3
29 Write a function LeftShift(Numlist, n)
in
Python, which acceptsthea list are
numeric value by which all elements of
of numbers and n is a
shifted to left.
list
Sample input data of the 60, 70], n=2
Numlist= [10, 20, 30, 40, 50,

Output 70, 10, 20]


Numlist-[30, 40, 50, 60,
a list of numbers. | 3
in Python PUSH(Num), where Num is
30.| Write a function numbers divisible by 5 into a stack implemented
by
From this list push all
stack if t has atleast one element, otherwise
display
a list. Display the
using
appropriate error message.
For example:
If the list Num is:
[66, 75, 40, 32, 10, 54]]
The stack should contain:

[75, 40, 10 OR MakePopPackage) to


MakePush(Package) and
Write functions in Python, Package Description,
Package and delete aPackage from a List of
add a new
pop operations of the Stack datastructure.
Considering them to act as push and
SECTION D India. Ithas | 5
its new data center in Delhi,
has to set up
31. An International Bank
five blocks of buildings
-

A, B, C, D and E.

B
A
E
each block areas
between the blocks and number of computers in
Distance
given below: (No of Computers
Distance Between Blocks

30m
Block A55
Block B to Block C Block B 1 8 0
30m
Block C to Block D Block C 60
35m
Block D to Block E
Block E toBlockkC_ 40m Block D 55
120m Block E 70
Block D to BlockA
Block D toBlockB | 45m
Block E to Block B 65m
your answer
() Suggest the most sultadle block to host the server. Justify connect various
Draw the cable layou slock to Block) to economically
(ii)
blocks within the Delhi campus of International Bank.
(iii) Suggest the placement the following devices with justification:
ot

(a) Repeater (b) Hub/Switch of


connect its head office in London. Which type
(iv)The bank is planning to or
network out of LAN, MAN, WAN will be formed? Justify your answer.
to be installed in the Delhi Campus to
take care
a device/software
(v) Suggest
of data security. code below and
32. (a) Consider the answerthe questions that follow:
def multiply(numberl, number2)
answer numberl* number2

return(answer)
print(number1, 'times', number2, '", answer)
output multiply(5, 5)

is executed, what gets printed?


G) When the code above
(ii) What is variable output equal
to after the code is executed?
record in the table Student:
b) The code given below inserts the following
Rollno integer
Name- string
Age -integer
between Python and
Note the following to establish connectivity
MYSQL:
Username is root
Password issys
base named school.
T h e table exists in a MYSQL data the user.
are to be accepted from
The details (Roll no, Name and Age)
Writethefollowingmissingstatementstocompletethecode:Statement 1- to

form the cursor object


S t a t e m e n t 2 - t o e x e c u t e t h e c o m m a n d t h a t i n s e r t s t h e r e c o r d i n t h e t a b l e S t u d e n t .

Statement3-toaddtherecordpermanentlyinthedatabase

import mysql.connector
mydb= mysql.connector.connect(host-"localhost",user="root"passwd="sys",

(8
database= "myschool)
#statement 1
mycursor =
while True:
ch-int(input("enter -1 to exit , any otner number to insert record"))
ifch1:
break
rollno =
int(input("enter Roll
no: "))
name= input("enter Name:")
ageint(input("enter Age:"))
values(&}AFAD.format(rollno,name,age)
qry= "insert into student
#statement 2
#statement 3
print("Data added successfully')
OR
code.
(a)Write the output of the following python
def convert(line):
n=len(line)
new_line = *"

for i in range(0,n):
if not line[i].isalpha)
new_line=new_line+ "@
else:
if linefi].isupper):
new_line= new_line + line[i]*2
else:
new_line =new_line +line[i]]
return new line
new_line= convert("Be 180 HuMan")
print(new_line)
inthetable Student, updates the data
(b) Thecodegivenbelowadds a new column table.
into it and displays the content of the
Student table details are asfollows:
Rollno- integer
Name-string
Age-integer
NotethefollowingtoestablishconnectivitybetweenPythonandMYSQL:

. Usernameisroot and Passwordis sys


.ThetableexistsinaMYSQLdatabasenamedschool.

Writethefollowingmissingstatementstocompletethecode:Statement1-to

formthecursor object
Statement2-toexecutea query that adds a column named "MARKS" of type
integer inthetableStudent.
Statement3-toupdatethere
rdpermanentlyinthedatabase
import mysql.comnector

mydb-mysql.comnecrConnect(host="localhost",
database="myschool")
user="root",passwd"sys",
mycursor #statementl
#statement2
mycursor.execute("update student set MARKS=9 where Rollno )
#statement3
mycursor.execute(select fTom student")
for x in mycursor:
print(x)
33. Write the full form of CSV. What is the default delimiter of csv files7
The scores and ranks of three students ofa school level programming
competition is given as:

[Name, Marks, 'Rank']


['Sheela', 450, 1]
['Rohan', 300, 2]
['Akash', 260, 3]
Write a program to do the following:
and write the it.
Create a csv file
(results.csv) above data into
(i)To display all the records present in the CSV file named 'results.csv'

OR

What does csv.writer object do? their Capitals" in which various


Rohan is making a software on "Countries &
records are to be stored/retrieved in CAPITAL.CSV data file. It consists some
records(Country & Capital). Help him to define and call the following user
defined functions:
add the records to a CSV
) AddNewRec(Country,Capital) -To accept and
file "CAPITAL.CSV". Each record consists of a list with field elements as
Country and Capital to store country name and capital name respectively.

(i) ShowRec0 -

To display all the records present in the CSV file named |


CAPITAL.cSv
SECTION E

34. | A company stores the records of motorbikes sold in January,February,


March | 1+1

(o 2es
and April months in MOTOR table as shown below +2

Bcode BnameJanuaryFebruaryMarch April


| 156 Honda 200 310 140 250
234 Pegasus 100 430 120 170
432 250 100 280
Ebony 340
876 Raven 300 150 240 430
970 Hero |250 130 190 100
Based on the data given above answer the following questions:

()Identify the most appropriate column, which can be considered as Primary


key.
(i)If3 more columns are added and 2 rows are deleted from the table
MOTOR, what will be the new degree and cardinality?
Cii) Write the query to:
(a) Insert the following record into the table
Bcode- 207, Bname- TVS, January- 500, February- 450,
March- 480, April - 350.

(b) Display the names of motor bikes which are sold more than 200 in
January month.
OR (Optionfor part ii only)

(ii) Write the query to:


(a) Add a new column MAY in MOTOR table with datatype as
integer.
(b) Display total number of Motorbikes sold in March Month.
35. | Sheela is a Python programmer. She has written a code and created a binary 1+1
file "book.dat" that has structure [BookNo, Book_Name, Author, Price]. The +2
following user defined function CreateFile0 is created to take input dáta for
a

record and add to book.dat and another user defined function


CountRec(Author) which accepts the Author name as parameter and count and
return number of books by the given Author.
code based the
Python expert, help her to complete the following
on
As a
requirement given above:

#statementl
import
def createFile():
fobj open("book.dat","_ " #statement2
BookNo int(input("Book number:"))
Book_Name = input("Book Name:")
Author=input("Author:")
Price i n t ( i n p u t ( " P r i c e : "

rec [BookNo, Book_Name


e, Author, Price]
pickle. #statement3
fobj.close0
def Count_Rec(Author):
fobj open("book.dat","rb")
num= 0

try:
while True:
rec pickle._ #statement4
i fAuthor=rec[2]:
num=num+1

except:
fobj.close0
return num

)Which module should be imported in the program? (Statement 1)


Write the correct statement required to open a file named book.dat.
(ii)
(Statement 2)
write the data into the
(iii) Which statement should be filled in Statement 3 to
data from the file,
binary file, book.dat and in Statement 4 to read the
book.dat?
KENDRIYA VIDYALAYA SANGATHAN, CHENNAI REGION
PRE-BOARD EXAM 2022-23
MARKING SCHEME
Class :XII Time : 3 hrs
Computer Science – (083) Max Marks : 70

General Instructions:
1.
This question paper contains five sections, Section A to E.
2.
All questions are compulsory.
3.
Section A have 18 questions carrying 01 mark each.
4.
Section B has 07 Very Short Answer type questions carrying 02 marks
each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal
choice is given in Q34 against part c only.
8. All programming questions are to be answered using Python Language
only.
SECTION A
1. State True or False: 1
“A dictionary key must be of a data type that is mutable.”
Ans: False
2. What will be the datatype of d, if d = (15) ? 1
(a) int (b) tuple (c) list (d) string

Ans: (a) int


3. Which of the following is a valid identifier in Python: 1
(a) elseif (b) for (c) pass (d) 2count

Ans: (a) elseif


4. Consider the given expression: 1
not 5 or 4 and 10 and ‘bye’
Which of the following will be correct output if the given expression
is evaluated?

(a) True
(b) False
(c) 10
(d) ‘bye’
Ans: (d) ‘bye’
5. Select the correct output of the code: 1
for i in "QUITE":
print([i.lower()], end= "#")

(a) q#u#i#t#e#
(b) [‘quite#’]
(c) ['q']#['u']#['i']#['t']#['e']#
(d) [‘quite’] #

Ans : ['q']#['u']#['i']#['t']#['e']#
6. Which file mode can be used to open a binary file in both append and 1
read mode?
a) w+ b) wb+ c) ab+ d) a+

Ans: (c) ab+


7. Fill in the blank: 1
The SQL built-in function _______ calculates the average of values in
numeric columns.
(a) MEAN() (b)AVG() (c) AVERAGE() (d) COUNT()

Ans: (b) AVG()


8. Which of the following commands will be used to select a particular 1
database named “Student” from MYSQL Database?
(a) SELECT Student;
(b) DESCRIBE Student;
(c) USE Student;
(d) CONNECT Student;
Ans: (c) USE Student;
9. Which of the following statement(s) would give an error after 1
executing the following code?
d = {"A" : 1, "B": 2, "C": 3, "D":4} #statement 1
sum_keys = 0 #statement 2
for val in d.keys(): #statement 3
sum_keys = sum_keys + val #statement 4
print(sum_keys)

(a) Statement 1
(b) Statement 2
(c) Statement 3
(d) Statement 4

Ans: (d) Statement 4


10. Fill in the blank: 1
An attribute in a relation is a foreign key if it is the ________ key in
any other relation.
(a) Candidate Key
(b) Foreign Key
(c) Primary Key
(d) Unique Key

Ans: (c) Primary Key


11. Which option correctly explains tell () method? 1
a) tells the current position within the file.
b) tells the name of file.
c) moves the current file position to a different location.
d) it changes the file position only if allowed to do so else returns an
error.

Ans: (a) tells the current position within the file.


12. Fill in the blank: 1
When two conditions must both be true for the rows to be selected, the
conditions are separated by the SQL keyword ________
(a)ALL (b)IN (c)AND (d)OR

Ans: (a) AND


13. Fill in the blank: 1
_________ protocol provides access to command line interface on a
remote computer.

(a) FTP (b) PPP (c) Telnet (d) SMTP

Ans: (c) Telnet


14. What will the following expression be evaluated to in Python? 1
print(25 // 4 + 3**1**2 * 2)

(a) 24 (b) 18 (c) 6 (d) 12

Ans: (d) 12
15. Which statement in SQL allows to change the definition of a table is 1
(a) Alter (b) Update. (c) Create (d) select

Ans: (a) Alter


16. The statement which is used to get the number of rows fetched by 1
execute() method of cursor:
(a) cursor.rowcount (b) cursor.rowscount()
(c) cursor.allrows() (d) cursor.countrows()
Ans: (a)cursor.rowcount
Q17 and 18 are ASSERTION AND REASONING based questions.
Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17. Assertion (A):- In Python, statement return [expression] exits a function. 1

Reasoning (R):- Return statement passes back an expression to the caller.


A return statement with no arguments is the same as return None.

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

18. Assertion (A): CSV module allows to write a single record into each 1
row in CSV file using writerow() function.
Reason (R): The writerow() function creates header row in csv file by
default.
Ans: (c) A is True but R is False
SECTION B
19. Rewrite the following code in python after removing all the syntax 2
errors. Underline each correction done in the code.
num1, num2 = 10
While num1 % num2 = 0
num1+= 20
num2+= 30
Else:
print(‘hello’)

Ans:
num1, num2 = 10, 45
while num1 % num2 == 0:
num1+= 20
num2+= 30
else:
print(‘hello’)

(½ Mark for each correction up to any 4 corrections)


20. Write two advantages and two disadvantages of circuit switching. 2
OR
Differentiate between Web server and web browser. Write any two
popular web browsers.
Ans:
Advantages:
1)A dedicated communication channel increases the quality of
communication.
2)Suitable for long continuous communication.
Disadvantages:
1)Resources are not utilized fully.
2)The time required to establish the physical link between the two
stations is too long.
½ mark for each advantage and disadvantage
OR
Web browser Web server
It is a type of software that we It is a type of software that
use for browsing and displaying searches, finds, and provides
web pages that might be documents to the browsers, as
available over the internet. requested by them.

A web browser acts as a link/ A web server functions to accept


interface between a client and a browser requests, generate
server. Its primary function is to responses, maintain the web
display various web documents apps, and accept the client data
to the clients requesting them.
Web browsers: Google Chrome, Mozilla Firefox
1 mark for difference and 1 mark for examples
21. Write two points of difference between ALTER and UPDATE 2
command in SQL.
Ans:
ALTER UPDATE
ALTER Command is used to UPDATE Command is used to
add, delete, modify the update existing records in a
attributes of the relations database.
(tables) in the database.
ALTER Command by default UPDATE Command sets
initializes values of all the tuple specified values in the
as NULL. command to the tuples.
This command make changes This command makes changes
with table structure. with data inside the table.

1 mark for each correct difference


22. (a) Given is a Python List declaration: 2
lst1= [39, 45, 23, 15, 25, 60].
What will be the output of :
print(lst1.index(23)) ?

(b) Write the output of the code given below:


x = [“rahul”, 5, “B”, 20, 30]
x.insert( 1, 3)
x.insert( 3, “akon”)
print(x[2])
Ans:
(a) 2
(b) 5
1 mark for each correct answer
23. (a) Write the full forms of the following: 2
(i) FTP (ii) HTTPS

(b)Name the protocols which are used for sending and receiving
emails?
Ans:
(a)
(i) FTP: File Transfer Protocol - ½ mark
(ii) HTTPS : Hyper Text Transfer Protocol Secure – ½ mark

(b)for sending emails – SMTP (Simple Mail Transfer Protocol)- ½


mark
For receiving emails- POP3 (Post Office Protocol Version 3) - ½
mark

24. Predict the output of the Python code given below: 2


st = "python programming"
count = 4
while True:
if st[0]== "p":
st = st[2:]
elif st[-2]=="n":
st = st[:4]
else:
count+=1
break
print(st)
print(count)
OR

Predict the output of the Python code given below:

myvalue = ["A", 40, "B", 60, "C", 20]


alpha = 0
beta = ""
gama = 0
for i in range(1,6,2):
alpha += i
beta += myvalue[i-1]+ "#"
gama += myvalue[i]
print(alpha, beta, gama)

Ans:
thon
5

OR
9 A#B#C# 120
25. What do you understand by the terms PRIMARY KEY and UNIQUE 2
KEY of a relation in relational database?
OR
Categorize the following commands as DDL or DML: DROP,
DELETE, SELECT, ALTER

Ans:
PRIMARY KEY: The PRIMARY KEY uniquely identifies each
record in a table. Primary keys contain UNIQUE values, and cannot
contain NULL values. A table can have only ONE primary key; and in
the table, this primary key can consist of single or multiple columns
(fields).

UNIQUE KEY: It Uniquely determines a row which isn’t primary key.


It can accept NULL values. More than one Unique keys can be defined
in one table.

1 mark for each correct explanation


OR
DDL – DROP , ALTER
DML- DELETE, SELECT
½ mark for each correct command
SECTION C
26. (a) Consider the following tables – Applicants and Centre 1+2

Table: Applicants
Appno Name Subject
C01 Mohan English
C02 Raju Hindi

Table : Centre

Appno City
C02 Madurai
C03 Chennai
C02 Jaipur

What will be the output of the following statement?

SELECT * FROM Applicants NATURAL JOIN Centre;

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

CCODE CNAME MAKE COLOUR CAPACITY CHARGES


105 Fortuner Toyota White 7 1500
245 Nexon Tata Black 5 1000
130 Duster Renault Green 6 2000
225 Kwid Renault Grey 5 2500
120 Baleno Suzuki Red 5 4000
207 Nano Tata Blue 4 3500

(i) SELECT DISTINCT MAKE FROM CAR;


(ii) SELECT MAKE, COUNT(*) FROM CAR GROUP BY MAKE;
(iii) SELECT CNAME FROM CAR WHERE CAPACITY>5 ORDER
BY CNAME;
(iv) SELECT CNAME, MAKE FROM CAR WHERE
CHARGES>2500;
Ans:
(a) 1 mark
Appno Name Subject City
C02 Raju Hindi Madurai
C02 Raju Hindi Jaipur

(b) ½ mark for each correct output


(i)
MAKE
Toyota
Tata
Renault
Suzuki

(ii)
MAKE COUNT(*)
Toyota 1
Tata 2
Renault 2
Suzuki 1

(iii)
CNAME
Duster
Fortuner

(iv)
CNAME MAKE
Baleno Suzuki
Nano Tata
27. Write a function in Phyton to read lines from a text file visiors.txt, and 3
display only those lines, which are starting with an alphabet 'P'.

If the contents of file is :

Visitors from various cities are coming here.


Particularly, they want to visit the museum.
Looking to learn more history about countries with their cultures.

The output should be:

Particularly, they want to visit the museum.


OR
Write a method in Python to read lines from a text file book.txt, to find
and display the occurrence of the word 'are'. For example, if the content
of the file is:

Books are referred to as a man’s best friend. They are very beneficial
for mankind and have helped it evolve. Books leave a deep impact on
us and are responsible for uplifting our mood.

The output should be 3.

Ans:
def rdlines():
file = open('visitors.txt','r')
for line in file:
if line[0] == 'P':
print(line)
file.close()

# Call the rdlines function.


rdlines()
½ mark for function header
1 mark for opening file
1 mark for correct for loop and condition
½ mark for closing file
OR
def count_word():
file = open('india.txt','r')
count = 0
for line in file:
words = line.split()
for word in words:
if word == 'India':
count += 1
print(count)
file.close()
# call the function count_word().
count_word()
½ mark for function header
1 mark for opening file
1 mark for correct for loop and condition
½ mark for closing file
28. (a) Consider the following tables EMPLOYEE and SALARY. 3
Table : EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
101 Akash Executive S03 2003-03-23 1980-01-13
102 Rajiv Manager S02 2010-02-12 1987-07-22
103 Jonny RO S03 2009-06-24 1983-02-24
104 Naziya GM S02 2006-08-11 1984-03-03
105 Pritam CEO S01 2004-12-29 1982-01-19
Table: SAL
SGRADE SALARY HRA
S01 56000 18000
S02 32000 12000
S03 24000 8000
Give the output of the following SQL queries:
(i) SELECT COUNT(SGRADE), SGRADE FROM EMPLOYEE
GROUP BY SGRADE;
(ii) SELECT MIN(DOB), MAX(DOJ) FROM EMPLOYEE;
(iii) SELECT NAME, SALARY FROM EMPLOYEE E, SAL S
WHERE E.SGRADE=S.SGRADE AND E.ECODE<103;
(iv) SELECT SGRADE, SALARY+HRA FROM SAL WHERE
SGRADE= ‘S02’;

(b) Write the command to view structure of table FOOD in a database.


Ans:
(i)
COUNT SGRADE
2 S03
2 S02
1 S01
(ii)
MIN(DOB) MAX(DOJ)
1980-01-13 2010-02-12
(iii)
NAME SALARY
Akash 24000
Rajiv 32000
(iv)
SGRADE SALARY+HRA
S02 44000
(b) DESCRIBE FOOD;
OR
DESC FOOD;
29. Write a function LeftShift(Numlist, n) in Python, which accepts a list 3
Numlist of numbers and n is a numeric value by which all elements of
the list are shifted to left.

Sample input data of the list


Numlist = [10, 20, 30, 40, 50, 60, 70], n=2
Output
Numlist = [30, 40, 50, 60, 70, 10, 20]
Ans:
def LeftShift(numlist, n):
L = len(numlist)
for x in range(0,n):
y = numlist[0]
for i in range(0,L-1):
numlist[i] = numlist[i+1]
numlist[L-1] = y
print(numlist)

or any other correct logic


30. Write a function in Python PUSH(Num), where Num is a list of 3
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has atleast one
element, otherwise display appropriate error message.

For example:
If the list Num is:
[66, 75, 40, 32, 10, 54]

The stack should contain:


[75, 40, 10]
OR
Write functions in Python, MakePush(Package) and
MakePop(Package) to add a new Package and delete a Package from
a List of Package Description, considering them to act as push and pop
operations of the Stack data structure.

Ans:
def PUSH(num): ½ mark
s=[]
for x in range(0, len(num)): 1 ½ mark
if num[x]%5 ==0:
s.append(num[x])
if len(s) == 0: 1 mark
print("Empty Stack")
else:
print(s)

PUSH([66,75,40,32,10,54])

OR
def MakePush(Package):
a= int(input("Enter package title:"))
Package.append(a)
def MakePop(Package):
if(Package ==[]):
print("Stack empty")
else:
print("deleted element:", Package.pop())

1 ½ for each function


SECTION D
31. An International Bank has to set up its new data center in Delhi, India. 5
It has five blocks of buildings – A, B, C, D and E.

A B C

D E

Distance between the blocks and number of computers in each block are
as given below:
Distance Between Blocks No of Computers
Block B to Block C 30m Block A 55
Block C to Block D 30m Block B 180
Block D to Block E 35m Block C 60
Block E to Block C 40m Block D 55
Block D to Block A 120m Block E 70
Block D to Block B 45m
Block E to Block B 65m

(i) Suggest the most suitable block to host the server. Justify your
answer.
(ii) Draw the cable layout (Block to Block) to economically connect
various blocks within the Delhi campus of International Bank.
(iii) Suggest the placement of the following devices with justification:
(a) Repeater (b) Hub/Switch

(iv)The bank is planning to connect its head office in London. Which


type of network out of LAN, MAN, or WAN will be formed? Justify
your answer.
(v) Suggest a device/software to be installed in the Delhi Campus to
take care of data security.

Ans:
(i) Block B
Justification- Block B has maximum number of computers. Reduce
traffic.
(ii)

A B C

D E

(iii) (a) between D and A blocks (b) in all the blocks


(iv) WAN
(v) Firewall
32. (a) Consider the code below and answer the questions that follow:

def multiply(number1, number2) :


answer = number1 * number2
return(answer)
print(number1, ‘times’, number2, ‘=’, answer)
output = multiply(5, 5)

(i) When the code above is executed, what gets printed?


(ii) What is variable output equal to after the code is executed?

(b) The code given below inserts the following record in the table
Student:

Rollno – integer
Name – string
Age – integer

Note the following to establish connectivity between Python and


MYSQL:
• Username is root
• Password is sys
• The table exists in a MYSQL database named school.
• The details (Rollno, Name and Age) are to be accepted from the
user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the
table Student.
Statement 3- to add the record permanently in the database

import mysql.connector
mydb=
mysql.connector.connect(host="localhost",user="root",passwd="sys",
database = “myschool”)
mycursor = ______________ #statement 1

while True:
ch=int(input("enter -1 to exit , any other number to insert record"))
if ch==-1:
break
rollno = int(input("enter Roll no:"))
name = input("enter Name:")
age = int(input("enter Age:"))
qry = "insert into student values
({},'{}',{})".format(rollno,name,age)
_________________________ #statement 2
_________________________ #statement 3
print(“Data added successfully”)

OR
(a)Write the output of the following python code.
def convert(line):
n = len(line)
new_line = ‘’
for i in range(0,n):
if not line[i].isalpha():
new_line = new_line + ‘@’
else:
if line[i].isupper():
new_line = new_line + line[i]*2
else:
new_line = new_line + line[i]
return new_line
new_line = convert(“Be 180 HuMan”)
print(new_line)

(b) The code given below adds a new column in the table Student,
updates the data into it and displays the content of the table.
Student table details are as follows:
Rollno – integer
Name – string
Age – integer

Note the following to establish connectivity between Python and


MYSQL:
• Username is root
• Password is sys
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute a query that adds a column named “MARKS”
of type integer in the table Student.
Statement 3- to update the record permanently in the database

import mysql.connector
mydb=
mysql.connector.connect(host="localhost",user="root",passwd="sys",
database="myschool")
mycursor = _____________________ #statement1
________________________________ #statement2
mycursor.execute("update student set MARKS=9 where Rollno = 1")
______________________________ #statement3
mycursor.execute("select * from student")
for x in mycursor:
print(x)

Ans:
(a)
(i) Nothing gets printed (as print( ) is after the return statement)
(ii) 25
(b)
Statement 1 :
mydb.cursor()

Statement 2:
mycursor.execute(qry)

Statement 3:
mydb.commit()
(1mark for each correct answer)

OR
(a) BBe@@@@@HHuMMan
(b)
Statement 1 :
mydb.cursor()

Statement 2:
mycursor.execute(“alter table student add column MARKS int”)

Statement 3:
mydb.commit()

(1mark for each correct answer)

33. Write the full form of ‘CSV’. What is the default delimiter of csv files? 5
The scores and ranks of three students of a school level programming
competition is given as:

[‘Name’, ‘Marks’, ‘Rank’]


[‘Sheela’, 450, 1]
[‘Rohan’, 300, 2]
[‘Akash’, 260, 3]

Write a program to do the following:


(i) Create a csv file (results.csv) and write the above data into it.
(ii)To display all the records present in the CSV file named ‘results.csv’

OR
What does csv.writer object do?
Rohan is making a software on “Countries & their Capitals” in which
various records are to be stored/retrieved in CAPITAL.CSV data file. It
consists some records(Country & Capital). Help him to define and call
the following user defined functions:
(i) AddNewRec(Country,Capital) – To accept and add the records to a
CSV file “CAPITAL.CSV”. Each record consists of a list with field
elements as Country and Capital to store country name and capital name
respectively.

(ii) ShowRec() – To display all the records present in the CSV file
named ‘CAPITAL.CSV’

Ans:
(a) CSV- Comma Seperated Values , default delimiter- comma (,)
1 mark
(b)
import csv
f = open("results.csv", "w")
cwriter = csv.writer(f) 2 marks
examdata = [["Name", "Marks", "Rank"],["Sheela", 450, 1],["Rohan",
300, 2],["Akash", 260, 3]]
cwriter.writerows(examdata)
f.close()

with open(“results.csv”,”r”) as NF:


NewReader=csv.reader(NF) 2 marks
for rec in NewReader:
print(rec[0], rec[1], rec[2])
OR

The csv.writer object adds delimitation to the user data prior to storing
data in the csv file on storage disk. –1 mark

import csv ½ mark


def AddNewRec(Country,Capital):
f=open(“CAPITAL.CSV”, “a”)
fwriter=csv.writer(f) 1½ marks
fwriter.writerow([Country,Capital])
f.close()
def ShowRec():
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv.reader(NF) 1 ½ marks
for rec in NewReader:
print(rec[0],rec[1])
AddNewRec(“INDIA”,”NEW DELHI”) ½ mark for calling both functions
AddNewRec(“JAPAN”,”TOKYO”)
ShowRec()
SECTION E
34. A company stores the records of motorbikes sold in January, February, 1+1
March and April months in MOTOR table as shown below: +2

Bcode Bname January February March April


156 Honda 200 310 140 250
234 Pegasus 100 430 120 170
432 Ebony 250 100 280 340
876 Raven 300 150 240 430
970 Hero 250 130 190 100

Based on the data given above answer the following questions:

(i) Identify the most appropriate column, which can be considered as


Primary key.
(ii) If 3 more columns are added and 2 rows are deleted from the table
MOTOR, what will be the new degree and cardinality?
(iii)Write the query to:
(a) Insert the following record into the table
Bcode- 207, Bname- TVS, January- 500, February- 450,
March- 480, April - 350.
(b) Display the names of motor bikes which are sold more than
200 in January month.
OR (Option for part iii only)

(iii) Write the query to:


(a) Add a new column MAY in MOTOR table with datatype as
integer.
(b) Display total number of Motorbikes sold in March Month.

Ans:
(i) Bcode
(ii) degree =9, cardinality =3
(iii) 1 mark for each
(a)INSERT INTO MOTOR VALUES(207, ‘TVS’, 500, 450, 480,
350);
(b) SELECT BNAME FROM MOTOR WHERE JANUARY>200;
OR
(iii) 1 mark for each
(a)ALTER TABLE MOTOR ADD MAY INT;
(b)SELECT SUM(MARCH) FROM MOTOR;
35. Sheela is a Python programmer. She has written a code and created a 1+1
binary file “book.dat” that has structure [BookNo, Book_Name, +2
Author, Price]. The following user defined function CreateFile() is
created to take input data for a record and add to book.dat and another
user defined function CountRec(Author) which accepts the Author
name as parameter and count and return number of books by the given
Author.
As a Python expert, help her to complete the following code based on
the requirement given above:

import ___________ #statement1


def createFile():
fobj = open("book.dat","________") #statement2
BookNo = int(input("Book number:"))
Book_Name = input("Book Name:")
Author = input("Author:")
Price = int(input("Price:"))
rec = [BookNo, Book_Name, Author, Price]
pickle.__________________ #statement3
fobj.close()
def Count_Rec(Author):
fobj = open("book.dat","rb")
num = 0
try:
while True:
rec = pickle._______________ #statement4
if Author == rec[2]:
num=num+1
except:
fobj.close()
return num

(i) Which module should be imported in the program? (Statement 1)


(ii) Write the correct statement required to open a file named book.dat.
(Statement 2)
(iii) Which statement should be filled in Statement 3 to write the data
into the binary file, book.dat and in Statement 4 to read the data from
the file, book.dat?
Ans:
(i) pickle 1 mark
(ii) ab 1mark
(iii) dump(rec, fobj) 1mark
load(fobj) 1 mark
KENDRIYA VIDYALAYA SANGATHAN
GUWHATI REGION
Pre – Board Examination: 2022-23
SET – I
Class: XII
SUBJECT: COMPUTER SCIENCE (083)
TIME: 03:00 HRS. MM: 70
General Instructions –
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q34 against part 3
only.
8. All programming questions are to be answered using Python Language only.

SECTION – A
1. State True or False
1
“Python language is Cross platform language.”
2. Which of the following is an invalid identifier in Python? 1
(a) Max_marks (b) Max–marks (c) Maxmarks (d) _Max_Marks
3. Predict the output. 1
marks = {"Ashok":98.6, "Ramesh":95.5}
print(list(marks.keys()))

(a) ‘Ashok’, ‘Ramesh’


(b) 98.6, 95.5
(c) [‘Ashok’,’Ramesh’]
(d) (‘Ashok’,’Ramesh’)
4. Consider the given expression: 1
not True and False or not True
Which of the following will be correct output if the given expression is evaluated?
(a) True
(b) False
(c) NONE
(d) NULL
5. Write the output:- 1
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
(a) #John#Peter#Vicky
(b) John#Peter#Vicky
(c) John#Peter#Vicky#
(d) #John#Peter#Vicky#
6. Which of the following mode in file opening statement results or generates an error if 1
the file does not exist?
(a) r+ (b) a+ (c) w+ (d) None of the above
7. Fill in the blank: 1
______ command is used to ADD a column in a table in SQL.
(a) update (b)remove (c) alter (d)drop
8. Which of the following is a DML command? 1
(a) CREATE (b) ALTER (c) INSERT (d) DROP
1|Page
9. Which of the following statement(s) would give an error after executing the following 1
code?
S="Welcome to my python program" # Statement 1
print(S) # Statement 2
S="Python is Object Oriented programming" # Statement 3
S= S * “5” # Statement 4
S=S+"Thank you" # Statement 5
(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5
10. Fill in the blank: 1
_________ is a non-key attribute, whose values are derived from the primary key of
some other table.
(a) Foreign Key
(b) Primary Key
(c) Candidate Key
(d) Alternate Key
11. Which SQL keyword is used to retrieve only unique values? 1
(a) DISTINCTIVE (b) UNIQUE (c) DISTINCT (d) DIFFEREN
12. The correct syntax of seek() is: 1
(a) file_object.seek(offset [, reference_point])
(b) seek(offset [, reference_point])
(c) seek(offset, file_object)
(d) seek.file_object(offset)
13. Fill in the blank: 1
______is a communication methodology designed to deliver electronic mail (E-mail)
over the internet.
.
(a) VoIP (b) HTTP (c) PPP (d) SMTP
14. What will the following expression be evaluated to in Python? 1
print(2**3 + (5 + 6)**(1 + 1))
(a) 129 (b)8 (c) 121 (d) None
15. Which function is used to display the total number of records from a table in a 1
database?
(a) sum(*)
(b) total(*)
(c) count(*)
(d) return(*)
16. Which of the following function is used to established connection between Python and 1
MySQL database –
(a) connection() (b) connect() (c) Connect() (d) None
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
Assertion (A): A binary file stores the data in the same way as as stored in the memory. 1
17.
Reason (R): Binary file in python does not have line delimiter.
Assertion (A):- If the arguments in a function call statement match the number and
order of arguments as defined in the function definition, such arguments are called
18. positional arguments. 1
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
2|Page
SECTION – B
Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
Num=int(rawinput("Number:"))
sum=0
for i in range(10,Num,3)
19. sum+=1 2
if i%2=0:
print(i*2)
else:
print(i*3)
print (Sum)
Write two points of difference between LAN & WAN.
20. OR 2
Write two points of difference between XML and HTML.
(a) Given is a Python string declaration:
str="CBSE Examination@2022"
Write the output of: print(str[-1:-15:-2])

21. (b) Write the output of the code given below: 2


d = {"name": "Akash", "age": 16}
d['age'] = 27
d['city'] = "New Delhi"
print(d.items())
Explain the use of ‘Primary Key’ in a Relational Database Management System. Give
22. 2
example to support your answer.
(a) Expand the following terms: SMTP, FTP
23. 2
(b) What do you mean by MODEM?
Predict output of the following code fragment –
def Change(P ,Q=30):
P=P+Q
Q=P-Q
print(P,"#",Q)
return(P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
24. S=Change(S) 2
OR
Predict output of the following code fragment –
tuple1 = (11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
Differentiate between count(column_name) and count(*) functions in SQL with
appropriate example.
25. OR 2
Categorize the following commands as DDL or DML:
SELECT, UPDATE, ALTER, DROP
3|Page
SECTION – C
(a) Consider the following tables – Sales and Item:
Table: Sales
SCode SName SCITY
S01 HITESH DELHI
S02 SANDEEP MUMBAI
S03 MAHESH BANGALORE

Table: Item
SCode IPRICE ICity
S01 1200 Delhi
S02 2500 Mumbai
S01 3200 Maharashtra

What will be the output of the following statement?

SELECT SNAME,SCITY,IPRICE FROM sales, Item where SCITY=”Delhi” and Sales.SCode


=Item.SCode;
1+
26. (b) Write the output of the queries (i) to (iv) based on the table, TABLE: EMPLOYEE 2=
3
TABLE: EMPLOYEE
EMPNO NAME DATE_OF_ JOINING SALARY CITY
5001 SUMIT SINGH 2012-05-24 55000 JAIPUR
5002 ASHOK SHARMA 2015-10-25 65000 DELHI
5003 VIJAY SINGH 2009-09-09 85000 JAIPUR
5004 RAKESH VERMA 2020-12-21 60000 AGRA
5006 RAMESH KUMAR 2011-01-22 72000 DELHI
(i) SELECT AVG(SALARY) FROM EMPLOYEE WHERE CITY LIKE ‘%R’;
(ii) SELECT COUNT(*) FROM EMPLOYEE
WHERE DATE_OF_JOINING BETWEEN ‘2011-01-01’ AND ‘2020-12-21’;
(iii) SELECT DISTINCT CITY FROM EMPLOYEE WHERE SALARY >65000;
(iv) SELECT CITY, SUM(SALARY) FROM EMPLOYEE GROUP BY CITY;

Write a method/function DISPLAYWORDS() in python to read lines from a text file


STORY.TXT, and display those words, which are less than 4 characters.
OR
Write a function RevText() to read a text file "Story.txt" and Print only word starting
27. with 'I' in reverse order. 3
Example:
If value in text file is:
INDIA IS MY COUNTRY
Output will be: AIDNI SI MY COUNTRY.
(a) Consider the following tables ACTIVITY and COACH.
2+
Write SQL commands for the statements (i) to (iv) and give the The outputs for the SQL
28. 1=
queries (v) to (viii) –
3
Table: ACTIVITY

4|Page
ACode ActivityName ParticipantsNum PrizeMoney ScheduleDate
1001 Relay 100X4 16 10000 23-Jan-2004
1002 High Jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discuss Throw 10 15000 19-Mar-2004

Table: COACH
PCode Name ACode
1 Ahmed Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003

(i) To display the name of all activities with their Acodes in descending order.
(ii) To display sum of prizemoney for each of the number of participants groupings (as
shown in column ParticipantsNum 10,12,16)
(iii) To display the coach’s name and ACodes in acending order of ACode from the table
COACH.
(iv) To display the content of the Activity table whose ScheduleDate is earlier than
01/01/2004 in ascending order of ParticipantsNum.

(b) Write the command to view all tables in a database.

Write a function SQUARE_LIST(L), where L is the list of elements passed as argument to


the function. The function returns another list named ‘SList’ that stores the Squares of
all Non-Zero Elements of L.
29. For example: 3
If L contains [9,4,0,11,0,6,0]
The SList will have - [81,16,121,36]

A list contains following record of a customer:


[Customer_name, Phone_number, City]

Write the following user defined functions to perform given operations on the stack
named ‘status’:
(i) Push_element() - To Push an object containing name and Phone number of
customers who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also,
display “Stack Empty” when there are no elements in the stack.

For example:
30. If the lists of customer details are: 3

[“Ashok”, “9999999999”,”Goa”]
[“Avinash”, “8888888888”,”Mumbai”]
[“Mahesh”,”77777777777”,”Cochin”]
[“Rakesh”, “66666666666”,”Goa”]

The stack should contain:


[“Rakesh”,”66666666666”]
[“Ashok”,” 99999999999”]
The output should be:

5|Page
[“Rakesh”,”66666666666”]
[“Ashok”,”99999999999”]
Stack Empty

OR

Vedika has created a dictionary containing names and marks as key-value pairs
of 5 students. Write a program, with separate user-defined functions to perform the
following operations:

(i) Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
(ii) Pop and display the content of the stack.

The dictionary should be as follows:

d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}

Then the output will be:


Umesh Vishal Ishika
SECTION – D

Ravya Industries has set up its new center at Kaka Nagar for its office and web based
activities. The company compound has 4 buildings as shown in the diagram below:

Distance between various blocks/locations:


Harsh to Raj Building 50m
Raj to Fazz Building 60m
Fazz to Jazz Building 25m
31. Jazz to Harsh Building 170m
Harsh to Fazz Building 125m
Raj to Jazz Building 90m

Number of computers in each building are -


Harsh – 15
Raj - 150
Fazz - 15
Jazz - 25

(i) Suggest a cable layout of connections between the buildings. 1


(ii) Suggest the most suitable place (i.e. building) to house the server of this 1
organisation with a suitable reason.
(iii) Suggest the placement of the following devices with appropriate reasons: 1
a. Hub / Switch
b. Repeater

6|Page
(iv) The organisation is planning to link its sale counter situated in various parts of 1
the same city, which type of network out of LAN, MAN or WAN will be formed?
Justify your answer.
(v) Suggest a device/software to be installed in the Campus to take care of data 1
security.
(a) Write the output of the code given below:

def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if s[i].isupper():
m=m+s[i].lower()
elif s[i].islower():
m=m+s[i].upper()
elif s[i].isdigit():
m=m+"O"
else:
m=m+'#'
print(m)
fun('CBSE@12@Exam')

(b) The code given below inserts the following record in the table EMP:
EmpID – integer
Name – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
is root
kvs 2+
32.
KVS. 3
EmpID, Name, Salary) are to be accepted from the user.

Write the following missing statements to complete the code:


Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table EMP.
Statement 3- to add the record permanently in the database

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",password="kvs", database="KVS")
mycursor=_________________ #Statement 1
eno=int(input("Enter Employee ID : "))
name=input("Enter name : ")
sal=int(input("Enter Salary : "))
querry="insert into EMP values({},'{}',{})".format(eno,name,sal)
______________________ # Statement 2
______________________ # Statement 3
print("Data Added successfully")

OR

7|Page
(a) Study the following program and select the possible output(s) from the options (i) to
(iv) following it.
Also, write the maximum and the minimum values that can be assigned to the
variable Y
import random
X= random.random()
Y= random.randint(0,4)
print(int(X),":",Y+int(X))
(i) 0 : 0
(ii) 1 : 6
(iii) 2 : 4
(iv) 0 : 3

(b) The code given below reads the following record from the table named student and
displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:

Write the following missing statements to complete the code:


Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose
marks are greater than 75.
Statement 3- to read the complete result of the query (records whose marks are
greater than 75) into the object named data, from the table student in the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",password="tiger",
database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()

What is the advantage of using a csv file for permanent storage?


Write a Program in Python that defines and calls the following user defined functions:
(i) ADDPROD() – To accept and add data of a product to a CSV file ‘product.csv’.
Each record consists of a list with field elements as prodid, name and price to store
product id, employee name and product price respectively.
33. (ii) COUNTPROD() – To count the number of records present in the CSV file named 5
‘product.csv’.
OR

Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:

8|Page
(i) add() – To accept and add data of a to a CSV file ‘stud.csv’. Each record
consists of a list with field elements as admno, sname and per to store admission
number, student name and percentage marks respectively.
(ii) search()- To display the records of the students whose percentage is more
than 75.

SECTION – D
Rashmi creates a table FURNITURE with a set of records to maintain the records of
furniture purchased by her. She has entered the 6 records in the table. Help her to find
the answers of following questions:-
FID NAME DATE OF PURCHASE COST DISCOUNT

B001 Double Bed 03-Jan-2018 45000 10


T010 Dining Table 10-Mar-2020 51000 5
B004 Single Bed 19-Jul-2021 22000 0
C003 Long Back Chair 6 30-Dec-2016 12000 3

T006 Console Table 17-Nov2019 15000 12 1+


34. 1+
B006 Bunk Bed 01-Jan-2021 28000 14 2

1. Identify the Primay Key from the given table with justification of your answer.
2. If three more records are added and 2 more columns are added, find the degree
and cardinality of the table.
3. (i) Write SQL command to insert one more data/record to the table
(ii) Increase the price of furniture by 1000, where discount is given more than 10.
OR (Option for part 3 only )
3. Write the statements to:
(a) Delete the record of furniture whose price is less than 20000.
(b) Add a column WOOD varchar with 20 characters.
Mr. Deepak is a Python programmer. He has written a code and created a binary
file “MyFile.dat” with empid, ename and salary. The file contains 15 records.
He now has to update a record based on the employee id entered by the user and
update the salary. The updated record is then to be written in the file “temp.dat”. The
records which are not to be updated also have to be written to the file “temp.dat”. If
the employee id is not found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the
requirement given above:

import _______ #Statement 1


def update_rec():
rec={}
35. 4
fin=open("MyFile.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update salary : "))
while True:
try:
rec=______________ #Statement 3
if rec["empid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary : "))
pickle.____________ #Statement 4
else:
9|Page
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()

(i) Which module should be imported in the program? (Statement 1)


(ii) Write the correct statement required to open a temporary file named temp.dat.
(Statement 2)
(iii) Which statement should Deepak fill in Statement 3 to read the data from the binary
file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?

######################

10 | P a g e
KENDRIYA VIDYALAYA SANGATHAN, JAIPUR REGION
Class: XII Session: 2022-23 Computer Science (083)
PRE-BOARD EXAMINATION-I-2022-23 [S-1]
Maximum Marks: 70 Time Allowed: 3 hours

General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is
given in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.

QNo SECTION-A Marks


1 Which command comes under TCL(Transaction Control Language)? 1
(a)alter (b)update (c) grant (d) create
2 Which of the following is an invalid datatype in Python?
(a) list (b) Dictionary (c)Tuple (d)Class 1
3 Given the following dictionaries
dict_fruit={"Kiwi":"Brown", "Cherry":"Red"}
dict_vegetable={"Tomato":"Red", "Brinjal":"Purple"}
Which statement will merge the contents of both dictionaries? 1

(a) dict_fruit.update(dict_vegetable) (b) dict_fruit + dict_vegetable


(c) dict_fruit.add(dict_vegetable) (d) dict_fruit.merge(dict_vegetable)
4 Consider the given expression:
not False and False or True
Which of the following will be correct output if the given expression is 1
evaluated?
True b.False c. NONE d. NULL
5 Select the correct output of the code:

(a) 0 1 2 ….. 15 (b)Infinite loop


(c) 0 3 6 9 12 15 (d) 0 3 6 9 12
6 Which of the following is not a valid mode to open a file?
1
(a) ab (b) r+ (c) w+ (d) rw
7 Fill in the blank:
command is used to delete the table from the database of SQL. 1
(a) update (b)remove (c) alter (d) drop
8 Which of the following commands will use to change the structure of table in
MYSQL database?
(a)DELETE TABLE (b)DROP TABLE 1
(c)REMOVE TABLE (d)ALTER TABLE
9 What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code?
import random
points=[20,40,10,30,15]
points=[30,50,20,40,45]
begin=random.randint(1,3) 1
last=random.randint(2,4)
for c in range(begin,last+1):
print(points[c],"#")
(a) 20#50#30# (b) 20#40#45
(c) 50#20#40# (d) both (b) and (c)
10 Fill in the blank:
is an attribute whose value is derived from the primary key
of some other table.
1
(a) Primary Key (b) Foreign Key
(c) Candidate Key (d) Alternate Key

11 The tell() function returns:


(a) Number of bytes remaining to be read from the file
(b) Number of bytes already read from the file
(c) Number of the byte written to the file 1
(d) Total number of bytes in the file

12 Fill in the blank:


The SELECT statement when combined with_________function,
returns number of rows present in the table. 1
(a) DISTINCT (b) UNIQUE (c) COUNT (d) AVG

13 Which switching technique follows the store and forward mechanism?


(a) Circuit switching (b) message switching
1
(c) packet switching (d) All of these

14 What will the following expression be evaluated to in Python?


print(16-(3+2)*5+2**3*4) 1
(a) 54 (b) 46 (c) 23 (d) 32
15 Which function is used to display the unique values of a column of a table?
1
(a) sum() (b) unique() (c)distinct() (d)return()
16 To establish a connection between Python and SQL database, connect() is
used. Which of the following value can be given to the keyword argument –
host, while calling connect ()?
(a) localhost 1
(b) 127.0.0.1
(c) any one of (a) or (b)
(d) localmachine
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct choice as-
(a) Both A and R are true and R is the correct explanation for A
1
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A):- key word arguments are related to the function calls.
Reasoning (R):- when you use keyword arguments in a function call, the 1
caller identifies the arguments by parameter name.
18 Assertion (A): CSV stands for Comma Separated Values
Reason (R): CSV files are a common file format for transferring and storing 1
data.
SECTION-B
19 Observe the following Python code very carefully and rewrite it after 2
removing all syntactical errors with each correction underlined.
DEF execmain():
x = input("Enter a number:")
if (abs(x)== x)
print("You entered a positive number")
else:
x=*1
print("Number made positive:" x )
20 Write two differences between Coaxial and Fiber transmission media. 2
OR
Write components of data communication.

21 (a) Given is a Python string declaration: 1+1 =2


message="Bring it on!!!"
Write the output of: print(message[::-2])
(b) Write the output of the code given below:
book_dict = {"title": "You can win", “copies”:15}
book_dict['author'] = “Shiv Khera”
book_dict['genre'] = "Motivation"
print(book_dict.items())
22 How many candidate key and primary key a table can have? Can we declare 2
combination of fields as a primary key?
23 (a) Write the full forms of the following: 1+1=2
(i) FTP (ii) MAC
(b) What is the use of TELNET?
24 Predict the output of the Python code given below: 2
def Swap (a,b ) :
if a>b:
print(“changed ”,end=“”)
return b,a
else:
print(“unchanged ”,end=“”)
return a,b
data=[11,22,16,50,30]
for i in range (4,0,-1):
print(Swap(data[i],data[i-1]))
OR
Predict the output of the Python code given below:
P = (10, 20, 30, 40, 50 ,60,70,80,90)
Q =list(P)
R = []
for i in Q:
if i%3==0:
R.append(i)
R = tuple(R)
print(R)
25 Differentiate between DDL and DML commands with suitable example. 2
OR
What is the difference between WHERE and HAVING clause of SQL
statement?
SECTION – C
26 (a)Consider the following tables – Bank_Account and Branch:
Bank_Account: 1+2=3
ACode Name Type
A01 Amit Savings
A02 Parth Current
A03 Mira Current
Branch:
ACode City
A01 Delhi
A02 Jaipur
A01 Ajmer
What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;
(b) Give the output of the following sql statements as per table given above.
Table : SPORTS
StudentNo Class Name Game1 Grade1 Game2 Grade2
10 7 Sammer Cricket B Swimming A
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Athletics C
i. SELECT COUNT(*) FROM SPORTS.
ii. SELECT DISTINCT Class FROM SPORTS.
iii. SELECT MAX(Class) FROM SPORTS;
iv. SELECT COUNT(*) FROM SPORTS GROUP BY Game1;

27 Write a method COUNTLINES() in Python to read lines from text file 1+2
‘TESTFILE.TXT’ and display the lines which are starting with any article (a,
an, the) insensitive of the case.
Example:
If the file content is as follows:
Give what you want to get.
We all pray for everyone’s safety.
A marked difference will come in our country.
The Prime Minister is doing amazing things.
The COUNTLINES() function should display the output as:
The number of lines starting with any article are : 2

OR

Write a function GPCount() in Python, which should read each character


of a text file “STORY.TXT” and then count and display the count of
occurrenceof alphabets G and P individually (including small cases g and
p too).
Example:
If the file content is as follows:

God helps those who help themselves.


Great way to be happy is to remain positive.
Punctuality is a great virtue.
The GPCount() function should display the output as:
The number of G or g: 3
The number of P or p : 6
28 (a) consider the following tables School and Admin and answer the following 2+1=3
questions:
TABLE: SCHOOL
CODE TEACHER SUBJECT DOJ PERIODS EXPERIENCE
1001 RAVI ENGLISH 12/03/2000 24 10
1009 PRIYA PHYSICS 03/09/1998 26 12
1203 LISA ENGLISH 09/04/2000 27 5
1045 YASH RAJ MATHS 24/08/2000 24 15
1123 GAGAN PHYSICS 16/07/1999 28 3
1167 HARISH CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16
TABLE : ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD

Give the output of the following SQL queries:


i. Select Designation, count(*) from Admin Group by Designation
having count(*)<2;
ii. Select max(experience) from school;
iii. Select teacher from school where experience >12 order by teacher;
iv. Select count(*), gender from admin group by gender;

(b) Write SQL command to delete a table from database.


29 Write a function Lshift(L), where L is the list of elements passes as an 3
argument to the function. The function shifts all the elements by one place
to the left and then print it.

For example:
If L contains [9,4,0,3,11,56]

The function will print - [4,0,3,11,56,9]


30 Write Add_New(Book) and Remove(Book) methods in Python to Add a new 1+2
Book and Remove a Book from a List of Books, considering them to act as
PUSH and POP operations of the data structure stack.
OR
Aalia has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the following operations
based on this list.
➢ Traverse the content of the list and push the even numbers into a stack.
➢ Pop and display the content of the stack.
For example:
If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be:
38 22 98 56 34 12
SECTION – D
31 Trine Tech Corporation (TTC) is a professional consultancy company. The 5
company is planning to set up their new offices in India with its hub at
Hyderabad. As a network adviser, you have to understand their requirement
and suggest them the best available solutions. Their queries
are mentioned
as (i) to (v) below.

a) Which will be the most appropriate block, where TTC should plan to
install their server?
b) Draw a block to block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.
c) What will be the best possible connectivity out of the following, you will
suggest to connect the new setup of offices in Bengalore with its London
based office.
● Satellite Link
● Infrared
● Ethernet
d) Which of the following device will be suggested by you to connect each
computer in each of the buildings?
● Switch
● Modem
● Gateway
e) Company is planning to connect its offices in Hyderabad which is less than
1 km. Which type of network will be formed?
32 (a) Write the output of the code given below: 2+3=5

(b)The code given below inserts the following record in the table
mobile:
import mysql.connector
mycon = mysql.connector.connect (host = “localhost”, user = “Admin”,
passwd = “Admin@123”, database = “connect”)
cursor = mycon. () # Statement 1
sql = “INSERT INTO Mobile (Name, Model, Price, Qty) VALUES (%s, %s, %s,
%s)” val = (“Samsung”, “Galaxy Pro”, 28000, 3)
cursor… (sql,val) #Statement 2
mycon. #Statement 3
Write the missing statement: Statement1 , Statement2 and Statement3
OR
(a) Predict the output of the code given below:

(b) The code given below reads the following record from the tablenamed
student and displays only those records who have marks greater than
80:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python andMYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named kvs.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object

Statement 2 – to execute the query that extracts records of thosestudents


whose marks are greater than 80.

Statement 3- to read the complete result of the query (records whose


marks are greater than 80) into the object named data, from thetable
studentin the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",passwo rd="tiger",
database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
33 (a) What does CSV stand for? 1+2+2=
(b) Write a Program in Python that defines and calls the following user 5
defined functions:
(i) InsertRow() – To accept and insert data of an student to a CSV file
‘class.csv’. Each record consists of a list with field elements as rollno,
name and marks to store roll number, student’s name and marks
respectively.
(ii) COUNTD() – To count and return the number of students who
scored marks greater than 75 in the CSV file named ‘class.csv’.
OR

Dhirendra is a programmer, who has recently been given a task to write a


python code to perform the following CSV file operations with the help of
two user defined functions/modules:

a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode


containing information of books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called BOOKS.CSV
where the field title starts with 'R'.
He has succeeded in writing partial code and has missed out certain
statements, so he has left certain queries in comment lines.

import csv
def CSVOpen():
with open('books.csv','_____',newline='') as csvf: #Statement-1
cw=_____________#Statement-2
__________________#Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=_________________#Statement-4
for r in cr:
if : #Statement-5 print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()

You as an expert of Python have to provide the missing statements and


other related queries based on the following code of Raman.

(i) Choose the appropriate mode in which the file is to be opened in


append mode (Statement 1)
(ii) Which statement will be used to create a csv writer object in
Statement 2.
(iii) Choose the correct option for Statement 3 to write the names of the
column headings in the CSV file, BOOKS.CSV.
(iv)
(iv) Which statement will be used to read a csv file in Statement 4.

(v) Fill in the appropriate statement to check the field Title starting with
‘R’ for Statement 5 in the above program.
SECTION -E
34 Mayank creates a table RESULT with a set of records to maintain the marks 4
secured by students in sub1, sub2, sub3 and their GRADE. After creation of
the table, he has entered data of 7 students in the table.
Table : RESULT
ROLL_NO SNAME sub1 sub2 sub3 GRADE
101 KIRAN 366 410 402 I
102 NAYAN 300 350 325 I
103 ISHIKA 400 410 415 I
104 RENU 350 357 415 I
105 ARPITA 100 75 178 IV
106 SABRINA 100 205 217 II
107 NEELIMA 470 450 471 I
103 ISHIKA 400 410 415 I
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as
Primary key.
(ii) If two columns are added and 2 rows are deleted from the table result,
what will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table
Roll No- 108, Name- Aaditi, sub1- 470, sub2-444, sub3- 475,
Grade– I.
b. Increase the sub2 marks of the students by 3% whose name
begins with ‘N’.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing Grade-IV.
b. Add a column REMARKS in the table with datatype as varcharwith 50
characters.
4
Reshabh is a programmer, who has recently been given a task to write a
35
python code to perform the following binary file operations with the help of
two user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing
student information – roll number, name and marks (out of 100) of each
student.
b. GetStudents() to display the name and percentage of those students
who have a percentage greater than 75. In case there is no student having
percentage > 75 the function displays an appropriate message. The function
should also display the average percent.
He has succeeded in writing partial code and has missed out certain
statements, so he has left certain queries in comment lines. You as an
expert of Python have to provide the missing statements and other related
queries based on the following code of Reshabh.

import pickle
def AddStudents():
_____________________# statement 1 to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
__________________#statement 2 to write the list L into the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
___________________ #statement 3 to read from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("No student has percentage more than 75")
print("average percent of class = ",_____________) #statement 4
AddStudents()
GetStudents()

(i) Which of the following commands is used to open the file “STUDENT.DAT”
for writing only in binary format? (marked as #1 in the Python code)
(ii) Which of the following commands is used to write the list L into the
binary file, STUDENT.DAT? (marked as #2 in the Python code)

(iii) Which of the following commands is used to read each record from the
binary file STUDENT.DAT? (marked as #3 in the Python code)

(iv) What expression will be placed in statement 4 to print the average


percent of the class.

************************
KENDRIYAVIDYALAYASANGATHANLUCKNOWREGION
Class:XIISession:2022-23
ComputerScience(083)
PREBOARD-1(Theory)
MaximumMarks:70 TimeAllowed:3hours
GeneralInstructions:
1. This question paper contains fivesections,Section AtoE.
2. Allquestions arecompulsory.
3. Section Ahas 18 questions carrying 01 mark each.
4. Section B has 07 VeryShort Answertype questions carrying 02 marks each.
5. Section Chas 05 Short Answer typequestions carrying 03 marks each.
6. Section Dhas 03 Long Answertype questionscarrying 05 marks each.
7. Section Ehas 02 questions carrying 04 markseach. Internal choice is given in Q34 for
part c only.
8. Allprogramming questions aretobe answered using Python Language only.
SECTIONA

1. Assign a tuplecontaining anInteger? 1

2. Which of the following is valid identifier? 1

a) Serial_no. b) total-Marks c) _Percentaged) Hundred$

3. Add a pair of parentheses toeach expressionso that itevaluates toTrue. 1

a) 2 + 3 == 4 +5 ==7 b) 0 ==1 == 2

4. What willbetheoutputof following expressions: 1

a) 2**3**2 b) (2**3)**2

5. Consider thefollowing programand predict the output: 1

num1 = input("Entera numberand I'll triple it: ") #num1=8

num1 = num1 *3

print(num1)

6. Which of the following is used toread n characters from afile object“ f1” . 1

a)f1.read(n) b)f1(2) c)f1(read,2) d) allof the above

7. Name DDL command from following. 1

a) drop b)select c) insert d)update

8. What is thedefaultdateformatof Mysql. 1

a)’ dd-mm-yy’ b)’ d-m-y ‘ c) ‘ yyyy-mm-dd’ d) None

9. Which of the following statement(s) would givean error afterexecuting thefollowing 1


code?
S="Lucknowis theCapital of UP"#Statement 1

print(S) #Statement2

S[4]= '$’ #Statement 3

S="Thank you" #Statement 4

S=S +"Thank you" #Statement 5

(a) Statement3 (b) Statement 4 (c) Statement 5 (d) Statement 4 and 5

10. _________ isan attribute,whosevalues areUnique and not null. 1

(a) Primary Key (b) Foreign Key (c) CandidateKey (d) AlternateKey

11. Which of the following statements correctly explain the function of seek() method? 1

a. tells the currentposition withinthefile.

b. determines if you canmovethefileposition or not.

c. indicates thatthenext read or writeoccurs from thatposition in a file.

d. movesthecurrentfileposition to agiven specified position.

12. What is break statement in the context of flowof control in the python programming. 1

13. SMTP stands for___________________________. 1

14. What willbetheoutputof this code 1

>>>L1=[8,11,20]

>>>L1*3

15. Write command toviewtable structure. 1

16. Name any twoRDBMSsoftware. 1

Q17 and 18 areASSERTIONAND REASONING based questions. Mark thecorrect


choiceas

(a) Both Aand R are trueand Ris the correctexplanation forA

(b) BothA and Raretrue and Ris not thecorrect explanation for A

(c) AisTruebutR is False

(d) AisFalsebutR is True

17. Assertion(A): Function is defined as a set of statements writtenunder a specific name 1


in the python code

Reason(R): The complete block (set of statements) is used at different instances in


theprogram as and when required, referring the function name. It is a common code to
executefor different values(arguments),provided to a function.

18. Assertion(A): DBMS is an application packagewhich arranges the data in orderly 1


mannerin a tabularform.

Reason(R): Itis an interfacebetweendatabaseand theuser. It allows theusers to


access and perform various operations on stored data using sometools.

SECTIONB

19. Rewritethefollowing codein python after removing all syntaxerror(s). Underlineeach 2


correction donein the code.

30=n

fori in range(0,n)

IF i%4==0:

print (i*4)

Else:

print (i+4)

20. Write twopointsof differencebetween hub and switch. 2

OR

Differentiate Bus and Startopology

21. (a) Given is aPython string declaration: 2

Str1="##NEET Examination 2023##"

Write the output of: print(Str1[::-1])

(b) Writetheoutputof the codegivenbelow:

D1 ={"sname":"Aman", "age": 26}

D1['age'] =27

D1['address'] = "Delhi"

print(D1.items())

22. DefineTupleand Attributewith appropriateexample. 2

23. Name twotop level domain names with theirarea of application. 2

24. What possible outputs(s) are expected to be displayed on screen at the time of 2
execution of the program from thefollowing code? Also specify the maximum values
thatcanbeassigned toeach of thevariables FROM and TO.
importrandom

AR=[20,30,40,50,60,70]

FROM=random.randint(1,3)

TO=random.randint(2,4)

for K in range(FROM,TO+1):

print(AR[K],end=” #“ )

(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

OR

What will be the output of thefollowing code?

def my_func(var1=100,var2=200):

var1+=10

var2 = var2 -10

return var1+var2

print(my_func(50),my_func())

25. Differentiatebetween char(n) and varchar(n) datatypes with respect todatabases. 2

OR

Consider thetable,student given below:

(a) Identify the degreeand cardinality of the table.

(b) Which field should bemade the primary key? Justify your answer.

SECTIONC

26. Meera has tocreatea databasenamed MYEARTHin MYSQL. Shenow needs tocreate 3
a tablenamed CITY in the database to store the records of variouscitiesacross the
globe. The tableCITY has the following structure:

Table: CITY

FIELDNAME DATATYPE REMARKS


CITYCODE CHAR(5) PrimaryKey

CITYNAME CHAR(30)

SIZE INTEGER(3)

AVGTEMP INTEGER

POLLUTIONRATE INTEGER

POPULATION INTEGER

Help hertocomplete the task bysuggesting appropriateSQLcommands.

27. Supposecontent of 'Myfile.txt' is 3

Humpty Dumpty sat on a wall

Humpty Dumpty had agreat fall

All the king's horses and all the king'smen

Couldn'tputHumpty togetheragain

Write apython function named RECORD to calculatetotalnumberof characters in


‘ Myfile.txt’

OR

Writea python function named CLRECORDtocalculate total numberof linesin


‘ Myfile.txt’

28. Write SQLCommand for the following. 3

a) Command used toviewthelistof tables in a database?

b) Command used toadd column in a database?

c) Command used to delete column from adatabase?

29. Write afunction in Python Convert() toreplaces elements having even values with its 3
half and elements having odd valueswith twice its valuein a list.

eg:if thelistcontains3,4,5,16,9 then

rearranged list as 6,2,10,8, 18

30. Write afunction in Python PUSH_IN(L), whereLis a list of numbers. Fromthislist,push 3


allnumbers which aremultipleof 3 intoa stack which is implemented by using another
list.

OR

Write afunction in Python POP(Arr),where Arris a stack implemented by a list of


numbers. Thefunction returns thevalue deleted fromthestack.

SECTIOND

31. Acompany ABCEnterprises has four blocks of buildings as shown: 5

B1 B2

B3 B4

Centretocenterdistancebetweenvariousblocks: Numberofcomputersineachblock: Co
B3 TO B1 50 M B1 150 mp
uter
B1 TO B2 60 M B2 15 sin

B2 TO B4 25 M B3 15 eac
h
B4 TO B3 170 M B4 25 blo
ck
B3 TO B2 125 M
are
B1 TO B4 90 M net
wor
ked but blocks are not networked. Thecompany has now decided toconnectthe
blocks also.

(i) Suggest the mostappropriatetopology for theconnectionsbetween the


blocks.

(ii) Thecompany wants internet accessibility in alltheblocks. The suitable

and cost-effectivetechnology for that would be?

(iii) Which devices will yousuggestforconnecting allthecomputers with in eachof


theirblocks.

(iv) Thecompany is planning to link itshead office situated in New Delhi with the
offices in hilly areas. Suggest a way to connect iteconomically.

(v) Suggest the mostappropriatelocation of theserver,toget the best


connectivity formaximumnumberof computers.
32. a) What willbetheoutputof following code: 2+3

def ChangeVal(M,N):

for i in range(N):

if M[i]%5 == 0:

M[i]//=5

if M[i]%3 == 0:

M[i]//=3

L= [25,8,75,12]

ChangeVal(L,4)

for i in L:

print(i,end="#")

b) Differentiatebetween Selection and Projection operations incontext of a Relational


Database. Also, illustratethedifferencewith onesupporting example of each.

OR

a)Find and write the output of thefollowing Python code:

def Call(P=40,Q=20):

P=P+Q

Q=P– Q

print(P,'@',Q)

return P

R=200

S=100

R=Call(R,S)

print(R,'@',S)

S=Call(S)

print(R,'@',S)

b) Differentiatedomain and attribute?Explain with appropriateexample?

33. What is thefull formof csv? Which applications are used toread/edit thesefiles? 5
Writea Program inPython thatdefines and calls the following user defined functions:

(i) ADDR() – To acceptand add data of a studenttoa CSV file‘ record.csv’ . Each
record consists of a list with field elementsas rollno, nameand mobiletostoreroll
number name and mobileno of studentrespectively.

(ii)COUNTR() – Tocount the number of records present intheCSVfile named


‘ record.csv’ .

OR

Give any onepoint of differencebetween a textfileand a csvfile.

Writea Program inPython thatdefines and calls the following user defined functions:

(i) add() – Toacceptand add data of an employee’ s furnituredetailtoa CSVfile


‘ abc.csv’ . Each record consists of alist with field elementsas fid,fnameand fprice
tostorefurnitureid, furniturename and furniturepricerespectively.

(ii) search()-Todisplay therecords of the furniturewhosepriceis morethan5000.

SectionE

34. Write SQLcommands for the following questions (i) to (iv) based on the relations 1+1
Teacher and Posting given below(assumenoconstraint isadded tothetable): +2

Table: Teacher

T_ID Name Age Department Date_of_join Salary Gender

1 Jugal 34 Computer Sc 10/01/2017 12000 M

2 Sharmila 31 History 24/03/2008 20000 F

3 Sandeep 32 Mathematics 12/12/2016 30000 M

4 Sangeeta 35 History 01/07/2015 40000 F

5 Rakesh 42 Mathematics 05/09/2007 25000 M

6 Shyam 50 History 27/06/2008 30000 M

7 ShivOm 44 Computer Sc 25/02/2017 21000 M

8 Shalakha 33 Mathematics 31/07/2018 20000 F

Table: Posting

P_ID Department Place

1 History Agra
2 Mathematics Raipur

3 ComputerScience Delhi

a)Toadd primary keyin Teacher(T_ID)

b)To add new attribute named P_IDtoTeacher table.

c)To add foreign key to newly created column P_ID in TeacherTable assuming that

whosevalues arereferred from P_ID column of posting table.

OR(option for partc) only)

c)To changedata typeof placecolumn of posting tablefromchar tovarchar.

35. Sumit is a Python programmer. He has written a code and created a binary file 1+1
record.dat with employeeid, ename and salary. The file contains 10 records. He now +2
has to update a record based on the employee id entered by the user and update the
salary. The updated record is then to be written in the file temp.dat. The records which
are not to be updated also have to be written to the file temp.dat. If the employee id is
not found, an appropriate message should to be displayed. As a Python expert, help
himtocompletethefollowing code based on therequirementgiven above:

import_______#Statement 1

def update_data():

rec={}

fin=open("record.dat","rb")

fout=open("_____________") #Statement2

found=False

eid=int(input("Enter employee id to updatetheir 14 salary ::"))

while True:

try:

rec=______________#Statement 3

if rec["Employee id"]==eid:

found=True

rec["Salary"]=int(input("Enternewsalary :: "))

pickle.____________ #Statement 4
else:

pickle.dump(rec,fout)

except:

break

if found==True:

print("Thesalary of employee id ",eid,"has beenupdated.")

else:

print("Noemployeewith such id is not found")

fin.close()

fout.close()

(i) Which module should beimported in theprogram? (Statement 1)

(ii) Write the correctstatement required to open a temporary file named temp.dat.
(Statement2)

(iii) Which statement should Aman fill in Statement 3 toread the data from the
binary file,record.datand in Statement 4 towritetheupdated datain thefile,
temp.dat?
Roll No. ………. KVP/083/B
KENDRIYA VIDYALAYA SANGATHAN, PATNA REGION
1st PRE BOARD EXAMINATION, 2022-23
CLASS – XII
COMPUTER SCIENCE
Max. Marks: 70 Time: 3 hrs
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice isgiven in Q35
against part c only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1. Identify the incorrect variable name: (1)
a) int b) float c) while d) true
2. What will be the data type of of the expression 12/5==0? (1)
a) True b) False c) bool d) float
3. What will be output of the following code: (1)
d1={1:2,3:4,5:6}
d2=d1.get(3,5)
print(d2)
a) 3 b) 4 c) 5 d) Error

4. Consider the given expression: (1)


8 and 13 > 10
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
5. Fill in the blank: (1)
command is used to remove a column from a table in SQL.
a) update b) remove c) alter d)drop
6. Which of the following mode in file opening statement generates an error ifthe file (1)
does not exist?
a) a+ b) r+ c) w+ d) None of these
7. Which of the following commands will delete a table from a MYSQL database? (1)
a) DELETE b) DROP c) REMOVE d) ALTER

8. Fill in the blank: (1)


An alternate key is a , which is not the primary key of the table.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key

1
9. Select the correct output of the code: (1)
a = "assistance"
a = a.partition('a')
b = a[0] + "-" + a[1] + "-" + a[2]
print (b)
a) -a-ssistance b) -a-ssist-nce
c) a-ssist-nce d) -a-ssist-ance

10. Which of the following statement(s) would give an error during execution? (1)
S=("CBSE") # Statement 1
S+="Delhi" # Statement 2
S[0]= '@' # Statement 3
S=S+"Thank you" # Statement 4
a) Statement 1 b) Statement 2 c) Statement 3 d) Statement 4

11. tell() is a method of: (1)


a) pickle module b) csv module c) file object d) seek()

12. Select the correct statement, with reference to RDBMS: (1)


a) NULL can be a value in a Primary Key column
b) '' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.

13. Which protocol is used for transferring files over a TCP/IP network? (1)
a) FTP b) SMTP c) PPP d) HTTP
14. What will the following expression be evaluated to in Python? (1)
27 % 7 // (3 / 2)
a) 2 b) 2.0 c) 4.0 d) 4
15. Which function cannot be used with string type data? (1)
a) min() b) max() c) count() d) sum()
16. In context of Python - Database connectivity, the function fetchmany()is a method of (1)
which object?
a) connection b) database c) cursor d) query
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for
c) A is True but R is False
d) A is false but R is True

17. Assertion (A):- print(f1()) is a valid statement even if the function f1() (1)
has no return statement.
Reasoning (R):- A function always returns a value even if it has no return
statement.

18. Assertion (A): If L is a list, then L+=range(5)is an invalid statement.Reason (R): Only (1)
a list can be concatenated to a list.

SECTION B

2
19. Mohit has written a code to input a positive integer and display its factorial. His code is (2)
having errors. Rewrite the correct code and underline the corrections made. (factorial of
a number n is the product 1x2x3. . .n)
n=int(input("Enter a positive integer: ")
f=0
for i in range(n):
f*=i
print(f)

20. Write two points of difference between LAN and MAN. (2)

OR

Write two points of difference between HTML and XML.

21. (a) Write a Python statement to display alternate characters of a string, named (1)
my_exam. For example, if my_exam="Russia Ukraine"
The statement should display Rsi kan

(b) Write the output of the code given below: (1)


d1 = {"name": "Aman", "age": 26}
d2 = d1.pop('name')
print(d1, d2)

22. Can a table in an RDBMS have multiple candidate keys? Can it have multiplePrimary (2)
keys? Give an example to support your answer.

23. (a) Write the full forms of the following: (i) VoIP (ii) IMAP (1)
(b) Name the communication medium which is used for WiFi. (1)

24. Predict the output of the Python code given below: (2)
def Alpha(N1): while
N1:
a=N1.pop()
if a%5>2: print(a,end='@') else: break
NUM=[13,24,12,53,34]
Alpha(NUM); print(NUM)
OR
Predict the output of the Python code given below:
T1 = tuple("Amsterdam")
T2, new_list = T1[1:-1], [] for i in T2:
if i in 'aeiou':
j=T1.index(i)
new_list+=[j]
print(new_list)

25. If a column score in a table match has five entries, viz. 30,65,NULL,40,NULL,then (2)
what will be the output of the following query?
Select count(*), avg(score) from match;
OR
Write two differences between HAVING and WHERE clauses in SQL.

3
SECTION C
26. (a) Consider the following table: (1)
Table: Employee

What is the degree and cardinality of table Employee, if it contains only the given
data? Which field fields is/are the most suitable to be the Primary key if the data
shown above is only the partial data? (2)
(b) Write the output of the queries (i) to (iv) based on the table Employee:
(i) select name, project from employee order by project;
(ii) select name, salary from employee where doj like'2015%';
(iii)select name, salary from employee where salary between 100000 and 200000;
(iv) select min(doj), max(dob) from employee;
27. Write a method count_words_e() in Python to read the content of a textfile and count (3)
the number of words ending with 'e' in the file.
Example: If the file content is as follows:
An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.
The count_words_e() function should display the output as:
No. of such words: 4
OR
Write a function reverseFile()in Python, which should read the content of a text file
“TESTFILE.TXT” and display all its line in the reverse order.

Example: If the file content is as follows:

It rained yesterday.
It might rain today.
I wish it rains tomorrow too.
I love Rain.

The RainCount() function should display the output as:

.yadretsey deniar tI
.yadot niar thgim tI
.oot worromot sniar ti hsiw I
.niaR evol I

4
28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relationsProjects (2)
and Employee given below:

(i) select project, count(*) from employee group by project;


(ii) select pid, pname, eid, name from projects p, employee e where
p.pid=e.project;
(iii) select min(startdate), max(startdate) from projects;
(iv) select avg(salary) from employee where doj between '2018-08-19'
and '2018-08-31';

(b) Write the command to make Projects column of employee table a foreign key (1)
which refers to PID column of Projects table.

29. Write a function AdjustList(L), where L is a list of integers. The function should reverse (3)
the contents of the list without slicing the list and without using any second list.
Example: If the list initially contains 2, 15, 3, 14, 7, 9, 19, 6, 1, 10,
then after reversal the list should contain 10, 1, 6, 19, 9, 7, 14, 3, 15, 2

5
30. A nested list contains the data of visitors in a museum. Each of the inner lists contains (3)
the following data of a visitor:
[V_no (int), Date (string), Name (string), Gender (String M/F), Age (int)]
Write the following user defined functions to perform given operations on the stack
named "status":
(i) Push_element(Visitors) - To Push an object containing Gender of visitor who
are in the age range of 15 to 20.
(ii) Pop_element() - To Pop the objects from the stack and count the display the
number of Male and Female entries in the stack. Also, display “Done” when
there are no elements in the stack.
For example: If the list Visitors contains:
[['305', "10/11/2022", “Geeta”,"F”, 35],
['306', "10/11/2022", “Arham”,"M”, 15],
['307', "11/11/2022", “David”,"M”, 18],
['308', "11/11/2022", “Madhuri”,"F”, 17],
['309', "11/11/2022", “Sikandar”,"M”, 13]]
The stack should contain
F
M

M
The output should be:
Done
Female: 1
Male: 2
OR
Write the following functions in Python:
(i) Push(st, expression), where expression is a string containing a valid
arithmetic expression with +, -, *, and / operators, and st is a list representing
a stack. The function should push all the operators appearing in this
expression into the stack st.
(ii) Pop(st) to pop all the elements from the stack st and display them.It should
also display the message 'Stack Empty' when the stack becomes empty.
For example: If the expression is:
42*5.8*16/24-8+2
Then st should contain
+
-
/
*
*
The output should be:
+ - / * * Stack Empty

6
31. FutureTech Corporation, a Bihar based IT training and development company, is
planning to set up training centers in various cities in the coming year. Their first center
is coming up in Surajpur district. At Surajpur center, they are planning to have 3
different blocks - one for Admin, one for Training and one for Development. Each
block has number of computers, which are required to be connected in a network for
communication, data and resource sharing. As a network consultant of this company,
you have to suggest the best network related solutions for them for issues/problems
raised in question nos. (i) to (v), keeping in mind the distances between various
blocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur (1)
center (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
(ii) Suggest why should a firewall be installed at the Surajpur Center? (1)
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to (1)
most efficiently connect various blocks within the Surajpur Center.
(iv) Suggest the placement of the following devices with appropriate reasons: (1)
a) Switch/Hub b) Router
(v) Suggest the best possible way to provide wireless connectivity between Surajpur
Center and Raipur Center. (1)

32. (a) Write the output of the code given below: (2)
p,q=8, [8]
def sum(r,s=5):
p=r+s
q=[r,s]
print(p, q, sep='@')
sum(3,4)
print(p, q, sep='@')

7
(b) The code given below accepts the increments the value of Clas by 1 foreach
student. The structure of a record of table Student is: (3)
RollNo – integer; Name – string; Clas – integer; Marks – integer
Note the following to establish connectivity between Python and MYSQL:
 Username is root, Password is abc
 The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:

import mysql.connector as mysql def sql_data():


con1=mysql.connect(host="localhost",user="root", password="abc")
#Statement 1
crsr.execute("use school")
#Statement 2
crsr.execute(querry)
# Statement 3
print("Data updated successfully")

Statement 1 – to create the cursor object.


Statement 2 – to create the query to update the table.
Statement 3- to make the updation in the database permanent
OR
(a) Predict the output of the code given below:
s="Rs.12"
n, m = len(s), ""
for i in range(0, n):
if s[i].islower():
m= m +s[i]
elif s[i].isupper():
m = m +s[i+1]
elif s[i].isdigit():
m = m*int(s[i])
else: m = '@'+m
print(m)

(b) The code given below reads records from the table named Vehicle and displays only
those records which have model later than 2010. The structure of a record of table
Vehicle is:
V_ID – integer; Name – string; Model – integer; Price – integer

Note the following to establish connectivity between Python and MYSQL:


 Username is root
 Password is abc
 The table exists in a MYSQL database named Transport.
 The details (RollNo, Name, Clas and Marks) are to be accepted from the
user.

Write the following missing statements to complete the code:


Statement 1 – to create the cursor object
Statement 2 – to execute the query that extracts records of those vehicles
whose model is greater than 2010.
Statement 3 - to read the complete result of the query into the object tnamed
data.

8
import mysql.connector as mysql
def display():
con1=mysql.connect(host="localhost",user="root", password="abc",
database="Transport")
#Statement 1
print("Students with marks greater than 75 are : ")
q="Select * from vehicle where model>2010"
#Statement 2
data= #Statement 3
for rec in data:
print(rec)
33. (a) What one advantage and one disadvantage of using a binary file for permanent (5)
storage?
(b) Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD() – To accept and add data of an item to a CSV file ‘events.csv’. Each
record consists of Event_id, Description, Venue, Guests, and Cost.
(ii) COUNTR() – To read the data from the file events.csv, calculate and display the
average number of guests and average cost.
OR
(a) Give any one point of difference between a binary file and a text file.
(b) Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an item to a binary file ‘events.dat’. Each
record of the file is a list [Event_id, Description, Venue, Guests, Cost].
Event_Id, Description, and venue are of str type, Guests and Cost are of
int type.
(ii) COUNTR() – To read the data from the file events.dat, calculate and display the
average number of guests and average cost.

SECTION E
34. Ifrah is a class XII student. She has created her Computer Science project in Python and (4)
saved the file with the name 'CarAgency.py'. Her code contains many blank lines.
Now she has written another Python script to remove all the bank lines from
'CarAgency.py' and to precede each line with a line number. For example, if
CarAgency.py originally contains:
import random, pickle

cars=[]

def estimate():
cost=0

Then after the program execution, the file 'CarAgency.py' should contain:
1. import random, pickle
2. cars=[]
3. def estimate():
4. cost=0

9
As a Python expert, help her to complete the following code (by completing
statements 1, 2, 3, and 4) based on the requirement given above.
(i) Statement-1 to import required functions.
(ii) Statement-2 to open temp.py in suitable mode.
(iii) Statement-3 to write line into temp.py
(iv) To delete CarAgency.py
from os #Statement 1
f1=open("CarAgency.py")
f2=open( , ) #Statement 2
i=1
for line in f1:
line=line.rstrip()
if len(line)>0:
line=str(i)+'.\t'+line+'\n'
i+=1
#Statement 3
f1.close()
f2.close()

#Statement 4
rename("temp.py","CarAgency.py")
35. Raghav has been assigned the task to create a database, named Projects. Healso has to (4)
create following two tables in the database:

Based on the given scenario, answer the following questions:

(i) Which table should he create first – Projects or Employee? Justify your answer.
(ii) What will be the degree of the Cartesian product of these two tables?
(iii) Write the SQL statement to create the table Employee.
(iv) Write the SQL statement to add a column Gender of type char(1) to the table
Employee, assuming that table Employee has already been created.
----------XXXXXXXXXX----------
10
KENDRIYA VIDYALAYA SANGATHAN, TINSUKIA REGION
Class: XII Session: 2022-23
Computer Science (083)
PREBOARD-I QUESTION PAPER (THEORY)
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice isgiven in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.

SECTION A
(Each question carries one mark)
1.What will be the output of the following python statement? 1
L=[3,6,9,12]
L=L+15
print(L)
(a)[3,6,9,12,15] (b) [18,21,24,27] (c) [5,3,6,9,12,15] (d) error

2.Identify the output of the following python statements 1


import random
for n in range(2,5,2):
print(random.randrange(1,n,end=’*’)
(a)1*3 (b) 2*3 (c) 1*3*4 (d)1*4

3.Which of the following is an invalid identifier? 1


(a)_123 (b) E_e12 (c) None (d) true

4.Consider the given expression: 1


7%5==2 and 4%2>0 or 15//2==7.5
Which of the following will be correct output if the given expression is evaluated?
(a)True (b) False (c)None (d)Null

5. Select the correct output of the code: 1


s = "Question paper 2022-23"
s= s.split('2')
print(s)
(a) ['Question paper ', '0', '', '-', '3']
(b) ('Question paper ', '0', '', '-', '3')
(c) ['Question paper ', '0', '2', '', '-', '3']
(d) ('Question paper ', '0', '2', '', '-', '3')

6. Which of the following mode in file opening statement does not results in Nor generates an error if the file
does not exist? 1
(a) r (b) r+ (c) w+ (d) None of the above

7.Which of the following commands is not a DDL command? 1


(a) DROP (b) DELETE (c) CREATE (d) ALTER

8.Which of the following SQL statements is used to open a database named “SCHOOL”? 1
(a) CREATE DATABASE SCHOOL;
Page 1
(b) USE DATABASE SCHOOL;
(c) USE SCHOOL;
(d) SHOW DATABASE SCHOOL;

9.Identify the output of the following python code: 1


D={1:”one”,2:”two”, 3:”three”}
L=[]
for k,v in D.items():
if ‘o’ in v:
L.append(k)
print(L)
(a) [1,2] (b) [1,3] (c)[2,3] (d)[3,1]

10.A relation can have only one______key and one or more than one______keys. 1
(a) PRIMARY, CANDIDATE
(b) CANDIDATE, ALTERNATE
(c )CANDIDATE ,PRIMARY
(d) ALTERNATE, CANDIDATE

11.Which of the following is the correct usage for tell() of a file object? 1
(a) It places the file pointer at the desired offset in a file.
(b)It returns the byte position of the file pointer as an integer.
(c)It returns the entire content of the file.
(d) It tells the details about the file.

12.What are the minimum number of attributes required to create a table in MySQL? 1
(a) 1 (b) 2 (c) 0 (d)3

13._____is a standard mail protocol used to receive emails from a remote server to a local email client. 1
(a) SMTP (b) POP (c) HTTP (d) FTP

14.Which of the following is not a tuple in python? 1


(a) (10,20) (b) (10,) (c) (10) (d) All are tuples.

15.SUM(), ANG() and COUNT() are examples of ______functions. 1


(a) single row functions
(b) multiple row functions
(c) math function
(d) date function

16.What are the mandatory arguments which are required to connect a MySQL database to python? 1
(a) username, password, hostname, database name
(b) username, password, hostname
(c) username, password, hostname, port
(d) username, password, hostname, database name

Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17.Assertion: The default value of an argument will be used inside a function if we do not pass a value to that
argument at the time of the function call. 1
Reason: the default arguments are optional during the function call. It overrides the default value if we provide
a value to the default arguments during function calls.
18. Assertion: Pickling is the process by which a Python object is converted to a byte stream. 1
Reason: load() method is used to write the objects in a binary file. dump() method is used to read data from a
binary file.

Page 2
SECTION B
Each Question Carry 2 marks
19. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in
the code.
2
30=Value
for VAL in range(0,Value)
If val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)

20.Write two points of difference between Bus Topology and Tree Topology. 2
OR
Write two points of difference between Packet Switching and Circuit Switching techniques?

21. (a) Given is a Python string declaration: 2


s=”Up Above The World So High”
Write the output of:
print(s[::-4])
(b)Write the output of the code given below:
D={‘month’:’DECEMBER’,’exam’:’PREBOARD1’}
D[‘month’]=’JANUARY’
D[‘EXAM’]=’PRE2’
print(D.items())

22. Differentiate between CHAR(N) and VARCHAR(N). 2

23. (a) Expand the following abbreviations: 2


i)POP ii)HTTPS
(b) What is a URL?

24. Predict the output of the Python code given below: 2


L=[4,6,7,1,6,9,4]
def fun(L):
for i in range(len(L)):
if(L[i]%3==0 and L[i]%2==0):
L[i]=L[i]+1
print(L)
return(L)
print(L)
k=fun()
print(k)
OR
Predict the output of the Python code given below:
T = (9,18,27,36,45,54)
L=list(T)
L1 = []
for i in L:
if i%6==0:
L1.append(i)
T1 = tuple(L1)
print(T1)

Page 3
25. Differentiate between WHERE and HAVING with appropriate examples. 2
OR
Differentiate between COUNT() AND COUNT(*) with appropriate examples.

SECTION C
Each Question Carry 3 Marks
26.(a)Write SQL query to add a column total price with datatype numeric and size 10, 2 in a table product.

1+2
(b) Consider the following tables SCHOOL and ADMIN. Give the output the following SQL queries:

i.SELECT Designation COUNT (*) FROM Admin GROUP BY Designation HAVING COUNT (*) <2;
ii.SELECT max (EXPERIENCE) FROM SCHOOL;
iii.SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY TEACHER;
iv.SELECT COUNT (*), GENDER FROM ADMIN GROUP BY GENDER;
27. Write a program to count the words “to” and “the” present in a text file “python.txt”. 3
OR
A text file “PYTHON.TXT” contains alphanumeric text. Write a program that reads this text file and writes to
another file “PYTHON1.TXT” entire file except the numbers or digits in the file.

28. (a)Sonal needs to display name of teachers, who have “0” as the third character in their name. She wrote
the following query. 1+2
SELECT NAME FROM TEACHER WHERE NAME = “$$0?”;
But the query is’nt producing the result. Identify the problem.
(b)Write output for (i) & (iv) based on table COMPANY and CUSTOMER.

Page 4
i. SELECT COUNT(*) , CITY FROM COMPANY GROUP BY CITY;
ii. SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10;
iii. SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
iv. SELECT PRODUCTNAME, CITY, PRICE FROM COMPANY, CUSTOMER
WHERE COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=”MOBILE”;

29. Write a function EVEN_LIST(L), where L is the list of elements passed as argument to the
function. 3
The function returns another list named‘evenList’ that stores the indices of all even numbers of L.

For example:
If L contains [12,4,3,11,13,56]
The evenList will have - [12,4,5]

30. Alfred has created a list, L containing marks of 10 students. Write a program, with separate user defined
function to perform the following operation: 3

PUSH()- Traverse the content of the List,L and push all the odd marks into the stack,S.
POP()- Pop and display the content of the stack.
Example: If the content of the list is as follows:
L=[87, 98, 65, 21, 54, 78, 59, 64, 32, 49]
Then the output of the code should be: 49 59 21 65 87
OR
Write a function in Python, Push(BItem) where , BItem is a dictionary containing the details of bakery items–
{Bname:price}.
The function should push the names of those items in the stack,S who have price less than 50.
For example:
If the dictionary contains the following data:
Bitem={"Bread":40,"Cake":250,"Muffins":80,"Biscuits":25}

The stack should contain


Bread
Biscuits

SECTION D
Each Question Carry 5 Marks
31. Perfect Edu Services Ltd. is an educational organization. It is planning to setup its India campus at Chennai
with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN, ENGINEERING,
BUSINESS and MEDIA. 5

You as a network expert have to suggest the best network related solutions for their problems raised in (i) to (v),
keeping in mind the distances between the buildings and other given parameters.

Page 5
(i) Suggest the most appropriate location of the server inside the CHENNAI campus (out of the 4
buildings), to get the best connectivity for maximum no. of computers. Justify your answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the CHENNAI
campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be installed to protect
and control the internet uses within the campus ?
(iv) Which of the following will you suggest to establish the online face-to-face communication
between the people in the Admin Office of CHENNAI campus and DELHI Head Office ?
(a) Cable TV
(b) Email
(c) Video Conferencing
(d) Text Chat
(v) Name protocols used to send and receive emails between CHENNAI and DELHI office?

32.(a) Suppose the contents of text file quotes.txt is: 2+3


“Believe you can and you will!”
What will be the output of the following python code?
F=open(“quotes.txt”)
F.seek(17)
S=F.read()
print(S.split(‘o’))
(b) Pikato wrote a program which he wants to use to connect with MySQL and show the name of the all the
record from the table “Student” from the database “School”. You are required to complete the statements so
that the code can be executed properly.

import_____.connector____pymysql # statement 1
dbcon=pymysql.__(host=”localhost”,user=”root”,__=”sia@1928”,__)# statement 2
if dbcon.isconnected()==False:
print(“Error in establishing connection:”)
cur=dbcon.______________() # statement 3
query=”select * from stmaster”
cur.execute(_________) # statement 4
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.______() # statement 5
OR
(a) Predict the output of the following python code snippet:
s="Hello2everyone"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)

Page 6
(b) Preety has written the code given below to read the following record from the table named employee and
displays only those records who have salary greater than 53500:
Empcode – integer
EmpName – string
EmpSalary – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is root@123
• The table exists in a MYSQL database named management.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those employees whose salary are greater than
53500.
Statement 3- to read the complete result of the query (records whose salary are greater than 53500) into the
object named data, from the table employee in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root", password="root@123",
database="management")
mycursor=_______________ #Statement 1
print("Employees with salary greater than 53500 are : ")
_________________________ #Statement2
data=__________________ #Statement 3
for i in data:
print(i)
print()

33. What is the advantage of using a csv file for permanent storage? 1+4
Write a Program in Python that defines and calls the following user defined
functions:
a) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a list
with field elements as empid, name and mobile to store employee id, employee name and employee salary
respectively.
b) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.

OR

Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
a) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists of a list
with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price
respectively.
b) search()- To display the records of the furniture whose price is more than 10000.

SECTION E
Each question carries 4 marks
34. Write a python program to create a csv file dvd.csv and write 10 records in it Dvdid, dvd name, qty, price.
Display those dvd details whose dvd price is more than 25. 4

35.Consider the table in Q26(b), write SQL Queries for the following: 4
i. To display TEACHERNAME, PERIODS of all teachers whose periods are more than 25.
ii. To display all the information from the table SCHOOL in descending order of experience.
iii. To display DESIGNATION without duplicate entries from the table ADMIN.
iv. To display TEACHERNAME, CODE and corresponding DESIGNATION from tables SCHOOL
and ADMIN of Male teachers.

Page 7
KENDRIYA VIDYALAYA SANGATHAN HYDERABAD REGION
PRE-BOARD 1 - EXAMINATION - 2022-23
Class: XII (COMPUTER SCIENCE -083)
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q34
against part C only.
8. All programming questions are to be answered using Python Language only.

SECTION A

1 What will be the result of the following statements? 1


a) bool(int(„0‟)) b) type(“hello”)
2 Which of the following is valid arithmetic operator in Python: 1
(a) // (b) ? (c ) < (d) and
3 Given the following dictionary 1
Emp1={„salary‟:10000,‟dept‟:‟sales‟,‟age‟:24,‟name‟:‟john‟}
Emp1.keys() can give the output as
a. („salary‟,‟dept‟,‟age‟,‟name‟)
b. [„name‟,„salary‟,‟dept‟,‟age‟]
c. [10000,‟sales‟,24,‟john‟]
d. {„salary‟,‟dept‟,‟age‟,‟name‟}

4 Consider the given expression: 1


(5<10)and(10<5)or(3<18)and not(8<18)
Which of the following will be correct output if the given expression is evaluated?

(a) True
(b) False
(c) NONE
(d) NULL
5 string= "it goes as - ringa ringa roses" 1
sub="ringa"
string.find(sub,15,22)
(a) 13 (b)-13 (c) -1 (d) 19
6 When the file content is to be retained , we can use the ____________ mode 1
(a) r (b) w (c) a (d) w+

7 Which of the following is NOT a DML Command? 1

(a) Insert (b) Update (c) Drop (d) Delete


8 Identify the error in the following SQL query which is expected to delete all rows of a table emp 1
without deleting its structure and write the correct one:

(a) DELETE TABLE emp;


(b) DROP TABLE emp;
(c) REMOVE TABLE emp;
(d) DELETE FROM emp;
9 What will be the Output for the following code – 1
Language=["C", "C++", "JAVA", "Python", "VB", "BASIC", "FORTRAN"]
del Language[4]
Language.remove("JAVA")
Language.pop(3)
print(Language)

(a) ['C', 'C++', 'VB', 'FORTRAN']


(b) ['C', 'C++', 'Python', 'FORTRAN']
(c) ['C', 'C++', 'BASIC', 'FORTRAN']
(d) ['C', 'C++', 'Python', 'BASIC']
10 All attribute combinations inside a relation that can serve as primary key are _______________ 1
(a) Primary Key
(b) Foreign Key
(c) Candidate Key
(d) Alternate Key
11 Which of the following statements correctly explain the function of tell() method? 1
(a) tells the current position within the file.
(b) tell the name of file.
(c) move the current file position to a different location.
(d) it changes the file position only if allowed to do so else returns an error

12 Which is known as range operator in MySQL? 1


(a) IN (b) BETWEEN (c) IS (d) DISTINCT
13 Network in which every computer is capable of playing the role of a client, or a server or both at same time 1
is called
a) local area network
b) peer-to-peer network
c) dedicated server network
d) wide area network
14 What will be the value of y when following expression be evaluated in Python? 1
x=10.0
y=(x<100.0) and x>=10
(a)110 (b) False (c)Error (d)True
15 All aggregate functions except _______ ignore null values in their input collection. 1
(a) Count (attribute)
(b) Count (*)
(c) Avg
(d) Sum
16 A database ___________is a special control structure that facilitates the row by row processing of 1
records in the result set.
(a) Fetch (b) table (c) cursor (d) query
Q17and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
(a) Both A and R are True and R is the correct explanation for A
(b) Both A and R are True and R is not the correct explanation for A
(c) A is True but R is False
(d) A is False but R is True
17 Assertion (A):-Built in functions are predefined in the language that are used directly. 1
Reasoning(R):-print() and input() are built in functions
18 Assertion (A):CSV file stands for Comma Separated Values. 1
Reason(R):CSV files are common file format for transferring and storing data
SECTIONB

19 Ravi has written a function to print Fibonacci series for first 10 elements. His code is having 2
errors. Rewrite the correct code and underline the corrections made. some initial elements of
Fibonacci series are:

def fibonacci()
first=0
second=1
print((“first no. is “, first)
print(“second no. is , second)
for a in range (1,9):
third=first+second
print(third)
first,second=second,third
fibonacci()
20 Give difference between Video Conferencing and Chatting 2
OR
Write two points of difference between Message Switching and Packet Switching

21 (a) Given is a Python string declaration: 1


str="malayalam"
Write the output of print(str[ : :-1])

(b) Write the output of the code given below:


Employee1={'name':'John','salary':10000,'age':24}
1
Employee2={'name':'Divya','salary':54000,'dept':'Sales'}
Employee1.update(Employee2)
print(Employee1)

22 Explain the use of „Primary key‟ in a Relational Database Management System. Give example to 2
support your answer.
23 (a) Write the full forms of the following: 2
(i)GSM (ii)XML
(b) What is the use of Modem?
24 (a) Predict the output of the Python code given below: 2

def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('[email protected]')

OR
(b)Predict the output of the Python code given below:

What is the output of the following Python code


x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])
25 Differentiate between WHERE and HAVING clause in MySql. 2
OR
What do you understand by the terms Degree, cardinality of a Relation? Explain with an example.

SECTION –C
26 (a) Differentiate between Natural join and Equi join. 1+2
(b)Table : Employee
EmployeeId Name Sales JobId
E1 SumitSinha 110000 102
E2 Vijay Singh 130000 101
Tomar
E3 Ajay Rajpal 140000 103
E4 Mohit Kumar 125000 102
E5 Sailja Singh 145000 103
Table: Job
JobId JobTitle Salary
101 President 200000
102 Vice President 125000
103 Administrator Assistant 80000
104 Accounting Manager 70000
105 Accountant 65000
106 Sales Manager 80000
Give the output of following SQL statement:
(i) Select Name, JobTitle, Sales from Employee, Job
where Employee.JobId=Job.JobId and JobId in (101,102);
(ii) Select JobId, count(*) from Employee group by JobId;

27 Write a method/function COUNT_BLANK_SPACES() in Python to read lines from a text file 3


STORY.TXT, and display the count of blank spaces in the text file.
OR
Write a method/function DISPLAYWORDS() in python to read lines from a text file POEM.TXT, and
display those words, which are less than 4 characters.

28 (a) Consider the following table GAMES. Give outputs for SQL queries (i) to (iv). 3
Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 CaromBoard 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 TableTennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 LawnTennis 4 25000 19-Mar-2004

(i) SELECT COUNT(DISTINCT Number) FROM GAMES;


(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;
(iv) SELECT * FROM GAMES WHERE PrizeMoney > 12000;

(b) What are the eligible candidate keys from the Table Games?

29 Write definition of a method/function DoubletheOdd( ) to add and display twice of odd values from 3
the list of Nums.
For example :
If the Nums contains [25,24,35,20,32,41]
The function should display
Twice of Odd Sum: 202
30 Pramod has created a dictionary containing EMPCODE and SALARY as key value pairs of 5 Employees of 3
Parthivi Constructions.
Write a program, with separate user defined functions to perform the following operations:
● Push the keys (Employee code) of the dictionary into a stack, where the corresponding value (Salary) is
less than 25000.
● Pop and display the content of the stack. For example: If the sample content of the dictionary is as follows:

EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000, "EOP4":15000, EOP5":30000}


The output from the program should be: EOP4 EOP3 EOP1
OR

Write a function POP(Arr) , where Arr is a stack implemented by a list of numbers The function returns the
value deleted from the stack.

SECTION D

31 Quick Learn University is setting up its academic blocks at Prayag Nagar and planning to set up a
network. The university has 3 academic blocks and one human resource Centre as shown in the
diagram given below:

Business Technology
Block Block

Law Block HR Centre

Centre-to-Centre distance between various blocks is as follows:


Law block to business block 40 m
Law block to technology block 80 m
Law block to HR block 105 m
Business block to technology block 30 m
Business block to HR block 35 m
Technology block to HR block 15 m

Number of computers in each of the buildings is as follows:


Law block 15
Technology block 40
HR Centre 115
Business block 25
(a) Suggest a cable layout of connection between the blocks.
1
(b) Suggest the most suitable place to house the server of the organization with suitable reason. 1
(c) Which device should be placed/installed in each of these blocks to efficiently connect all the
1
computers within these blocks?
(d) The university is planning to link its sales counters situated in various parts of the CITY. Which
1
type of network out of LAN, MAN or WAN will be formed?
1
(e) Which network topology may be preferred between these blocks?
32 (a) Find and write the output of the following python code: 2+3
def Change(P ,Q=10):
P=P*Q
Q=Q+P
print( P,"#",Q)
return (Q)
A=5
B=10
A=Change(A)
B=Change(A,B)
print(A,"#",B)
(b) Avni is trying to connect Python with MySQLfor her project.
Help her to write the python statement on the following:-
(i) Name the library, which should be imported to connect MySQL with Python.
(ii)Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having the arguments values as :
Host name :192.168.11.111 User : root
Password: Admin Database : MYPROJECT
OR
(a)Find and write the output of the following python code:
def encrypt(s):
k=len(s)
m=""
for i in range(0,k):
if(s[i].isupper( )):
m=m+str(i)
elif s[i].islower( ):
m=m+s[i].upper()
else:
m=m+'*'
print(m)
encrypt('Kvs@Hyderabad')
(b)Note the following to establish connectivity between Python and MYSQL:
 Username is myusername
 Password is mypassword
 The table exists in a MYSQL database named mydatabase
Write the following missing statements to complete the code:
Statement 1 – to create the connection object
Statement2–tocreate the cursor object
Statement3-To execute the sql query
import mysql.connector
mydb = _____________________________ # Statement 1
mycursor = _______________ # Statement 2
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor._________________ # Statement 3
mydb.commit()
print(mycursor.rowcount, "record inserted.")
33 Manoj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain
5
user name and password for some entries. He has written the following code. As a programmer,
help him to successfully execute the given task.
import ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close( )
# csv file reading code
def readCsvFile(): #to read data from CSV file
with open('user.csv','r') as newFile:
newFileReader=csv.______(newFile) #Line3
for row in newFileReader:
print(row)
newFile.________________ #Line4
addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()
OUTPUT___________________ #Line 5
(a) What module should be imported in #Line1 for successful execution of the program?
(b) In which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file
(e) Write the output he will obtain while executing Line5
OR
Radha Shah is a programmer, who has recently been given a task to write a python code to perform
the following CSV file operations with the help of two user defined functions/modules:

(a) . CSVOpen() : to create a CSV file called “ books.csv” in append mode containing
information of books – Title, Author and Price.
(b). CSVRead() : to display the records from the CSV file called “ books.csv” .where the field
title starts with 'R'.
She has succeeded in writing partial code and has missed out certain statements, so she has left
certain queries in comment lines.
import csv
def CSVOpen( ):
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead( ):
try: with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')
CSVOpen( )
CSVRead( )

You as an expert of Python have to provide the missing statements and other related queries based
on the following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Which statement will be used to create a csv writer object in Statement 2.
(c) Write the correct option for Statement 3 to write the names of the column headings in the CSV
file, books.csv
(d) Write statement to be used to read a csv file in Statement 4.
(e) Fill in the appropriate statement to check the field Title starting with „R‟ for Statement 5 in the
above program.

SECTION –E
34 A departmental store MyStore is considering to maintain their inventory using SQL to store the 1+1+
data. As a database Administrator, Abhay has decided that: 2
Name of the database – mystore
Name of the table –STORE
The attributes of STORE are as follows
ItemNo –numeric
ItemName – character of size 20
Scode – numeric
Quantity – numeric

Table : STORE
ItemNo ItemName Scode Quantity

2005 Sharpner Classic 23 60


2003 Ball Pen 0.25 22 50
2002 Gel Pen Premium 21` 150
2006 Gel Pen Classic 21 250
2001 Eraser Small 22 110
2004 Eraser Big 22 220
2009 Ball Pen 0.5 21 180

(a) Identify the attribute best suitable to be declared as primary key


(b) Write the query to add the row with following details
(2010,”Notebook”,23,155)
(c) (i) Abhay wants to remove the table STORE from the database MyStore, Help Abhay in writing
the command for removing the table STORE from the database MyStore.
(ii) Now Abhay wants to display the structure of the table STORE i.e. name of the attributes
and their respective data types that he has used in the table. Write the query to display the
same.
OR
(i) Abhay wants to ADD a new column price with data type as decimal. Write the query to add
the column..
(ii) Now Abhay wants to remove a column price from the table STORE. Write the query.

35 Manoj is learning to work with Binary files in Python using a process known as Pickling/de-
pickling. His teacher has given him the following incomplete code, which is creating a Binary file
namely Mydata.dat and then opens, reads and displays the content of this created file.

import____________#Statement-1
sqlist=list()
for k in range(5): sqlist.append(k*k)
fout=open(“mydata.dat”,____________) #Statement-2
_____________(sqlist,fout) #Statement-3
fout.close()
fin=open(“Mydata.dat”, “rb” )
mylist= _________________(fin) #Statement-4
fin.close()
print(mylist)

1
i) Which module should be imported in Statement-1.
1
ii) Which file mode to be passed to write data in file in Statement-2
iii) What should be written in Statement-3 to write data onto the file. 1
iv) Which function to be used in Statement-4 to read the data from the file. 1
KENDRIYA VIDYALAYA SANGATHAN HYDERABAD REGION
PRE-BOARD - EXAMINATION - 2022-23
Class: XII (Comp.Sc -083)
MARKING SCHEME
Maximum Marks: 70 TimeAllowed:3hours

SECTION A
1 What will be the result of the following statements? 1
a) bool(int(„0‟)) b) type(“hello”)
ans 1
a) False
b) <class str‟>
2 Which of the following is valid arithmetic operator in Python: 1
(a) // (b) ? (c ) < (d) and
ans (a) // 1
3 Given the following dictionary

Emp1={„salary‟:10000,‟dept‟:‟sales‟,‟age‟:24,‟name‟:‟john‟}
Emp1.keys() can give the output as
a. („salary‟,‟dept‟,‟age‟,‟name‟)
b. [„salary‟,‟dept‟,‟age‟,„name‟]
c. [10000,‟sales‟,24,‟john‟]
d. {„salary‟,‟dept‟,‟age‟,‟name‟}
ans b.[„salary‟,‟dept‟,‟age‟,„name‟] 1
4 Consider the given expression: 1
(5<10)and(10<5)or(3<18)and not (8<18)
Which of the following will be correct output if the given expression is evaluated?

(a) True
(b) False
(c) NONE
(d) NULL
ans b) False 1
5 string= "it goes as - ringa ringa roses"
sub="ringa"
string.find(sub,15,22)
(a) 13 (b)-13 (c) -1 (d) 19
ans (c) -1 1
6 When the file content is to be retained, we can use the ____________ mode 1
(a) r (b) w (c) a (d) w+

ans (c) a
7 Which of the following is NOT a DML Command? 1

(a) Insert (b) Update (c) Drop (d) Delete

ans (c) Drop 1


8 Identify the error in the following SQL query which is expected to delete all rows of a table emp 1
without deleting its structure and write the correct one:
(a) DELETETABLE;
(b) DROPTABLE emp;
(c) REMOVETABLE emp;
(d) DELETE FROM emp;
ans (d) DELETE FROM emp; 1
9 What will be the Output for the following code –
Language=["C", "C++", "JAVA", "Python", "VB", "BASIC", "FORTRAN"]
del Language[4]
Language.remove("JAVA")
Language.pop(3)
print(Language)

(a) ['C', 'C++', 'VB', 'FORTRAN']


(b) ['C', 'C++', 'Python', 'FORTRAN']
(c) ['C', 'C++', 'BASIC', 'FORTRAN']
(d) ['C', 'C++', 'Python', 'BASIC']
ans (b) ['C', 'C++', 'Python', 'FORTRAN'] 1
10 All attribute combinations inside a relation that can serve as primary key are _______________ 1
(a) Primary Key
(b) ForeignKey
(c) CandidateKey
(d) AlternateKey
ans (c) Candidate Key 1
11 Which of the following statements correctly explain the function of tell() method?
(a) tells the current position within the file.
(b) tell the name of file.
(c) move the current file position to a different location.
(d) it changes the file position only if allowed to do so else returns an error
ans (a) tells the current position within the file. 1

12 Which is known as range operator in MySQL? 1


(a) IN (b) BETWEEN (c) IS (d) DISTINCT
ans (b) BETWEEN 1
13 Network in which every computer is capable of playing the role of a client, or a server or both at same time 1
is called
a)local area network
b)peer-to-peer network
c)dedicated server network
d)wide area network
ans b)peer-to-peer network 1
14 What will be the value of y when following expression be evaluated in Python? 1
x=10.0
y=(x<100.0) and x>=10
(a)110 (b) False (c)Error (d)True
ans (d) True 1
15 All aggregate functions except _______ ignore null values in their input collection. 1
(a) Count (attribute)
(b) Count (*)
(c) Avg
(d) Sum
ans (b) Count (*) 1
16 A database ___________is a special control structure that facilitates the row by row processing of 1
records in the result set.
(a) Fetch (b) table (c) cursor (d) query
ans (c) cursor 1
Q17and18areASSERTIONANDREASONINGbasedquestions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion(A):-Built in functions are predefined in the language that are used directly. 1
Reasoning(R):-print() and input() are built in functions
ans (b) Both A and Rare true and R is not the correct explanation for A 1

Explanation: The python built in functions are defined as the functions whose functionality is
predefined. The python interpreter has several functions that are always present for use.
Example: print() and input() are built in functions
18 Assertion(A):CSV file stands for Comma Separated Values. 1
Reason(R):CSV files are common file format for transferring and storing data
ans (b) Both A and R are true and R is not the correct explanation for A 1

Explanation: The ability to read , manipulate and write data to and from CSV files using python
is a key skill to master for any data Scientist and Business analysis.
SECTIONB
19 Ravi has written a function to print Fibonacci series for first 10 element. His code is having 2
errors. Rewrite the correct code and underline the corrections made. some initial elements of
Fibonacci series are:

def fibonacci()
first=0
second=1
print((“first no. is “, first)
print(“second no. is , second)
for a in range (1,9):
third=first+second
print(third)
first,second=second,third
fibonacci()
ans def fibonacci( ): # missing colon 2
first=0
second=1
print(“first no. is “, first) # extra parenthesis
print(“second no. is”, second) # closing quotes is missing
for a in range (1,9):
third=first+second
print(third)
first,second=second,third
fibonacci( ) # fuction call indentation is wrong
20 Give difference between Video Conferencing and Chatting 2
OR
Write two points of difference between Message Switching and Packet Switching
ans Video conference Chatting 2
Audio as well Visuals are shared Only text communicated
High Bandwidth required Works with low bandwidth also
Protocols: SIP, H.323 Protocol: IRC( Internet relay chat)

Or
Message Switching Packet Switching
In message switching data is stored in In this form of switching data is
buffer form. transferring into packet form.
The message is, sent to the nearest A fixed size of packet that can be
directly connected switching node. transmitted across the network is
This process continues until data is specified.
delivered to the destination computer.
Stored in disk All the packets are stored in the main
memory instead of disk.
Ex: sms Ex:E mail

21 (a) Given is a Python string declaration: 1


str="malayalam"
Write the output of :print(str[: :-1])

(b) Write the output of the code given below:


1
Employee1={'name':'John','salary':10000,'age':24}
Employee2={'name':'Divya','salary':54000,'dept':'Sales'}
Employee1.update(Employee2)
print(Employee1)
ans (a)"malayalam" 1
(b){'name': 'Divya', 'salary': 54000, 'age': 24, 'dept': 'Sales'} 1
22 Explain the use of„Primary key‟ in a Relational Database Management System. Give example to 2
support your answer.
ans A Primary Key is a set of one or more attributes that can uniquely identify tuples within the 2
relation .
Ex: Adminno. From student table or any other suitable example.
(1 mark for explanation and 1 mark for example) ( Any relevant correct example may be
marked)
23 (a) Write the full forms of the following: 2
(i)GSM (ii)XML
(b) What is the use of Modem?
ans (a) (i) GSM: Global system for mobile computing 1
(ii) XML: Extensible Mark up Language

(b) Modem:A modem is a device that modulates or demodulates the signal. · It acts as a bridge 1
between the internet/telephone line and the computer
24 (a) Predict the output of the Python code given below: 2
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('[email protected]')
OR
(b)Predict the output of the Python code given below:
What is the output of the following Python code
x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])
ans (a)fUN#wORLD#2# 2
OR

(b)he hello wor ld


w ll
llo wo or
25 Differentiate between WHERE and HAVING clause in MySql. 2
OR
What do you understand by the terms Degree , cardinality of a Relation? Explain with an example.
ans WHERE Clause is used to filter the records from the table or used while joining more than one 2
table. Only those records will be extracted who are satisfying the specified condition in WHERE
clause. It can be used with SELECT, UPDATE, DELETE statements.
HAVING Clause is used to filter the records from the groups based on the given condition in the
HAVING Clause. Those groups who will satisfy the given condition will appear in the final
result. It can be used only with GROUP BY clause.
OR
Degree: No. of columns(attribute) of a table
Cardinality: No.of rows( Tuples) of a table
Ex: EMP Table
EmployeeId Name Sales JobId
E1 Sumit Sinha 110000 102
E2 Vijay Singh 130000 101
Tomar
E3 Ajay Rajpal 140000 103

Degree- 4
Cardinality- 3
(Any other suitable example)

26 (a) Differentiate between Natural join and Equi join. 1+


(b)Table : Employee 2

EmployeeId Name Sales JobId


E1 SumitSinha 110000 102
E2 Vijay Singh 130000 101
Tomar
E3 Ajay Rajpal 140000 103
E4 Mohit Kumar 125000 102
E5 Sailja Singh 145000 103
Table: Job
JobId JobTitle Salary
101 President 200000
102 Vice President 125000
103 Administrator Assistant 80000
104 Accounting Manager 70000
105 Accountant 65000
106 Sales Manager 80000
Give the output of following SQL statement:
(i) Select Name, JobTitle, Sales from Employee, Job
where Employee.JobId=Job.JobId and JobId in (101,102)
(ii) Select JobId, count(*) from Employee group by JobId
ans (a) Equi Join displays the common column twice , where as the Natural join displays the
common column only once in the Join query.
(b) (i)

Name JobTitle Sales


Vijay Singh Tomar President 130000
SumitSinha Vice President 110000
Mohit Kumar Vice President 125000

(ii)
JobId Count(*)
101 1
102 2
103 2
27 Write a method/function COUNT_BLANK_SPACES() in Python to read lines from a text file 3
STORY.TXT, and display the count of blank spaces in the text file.
OR
Write a method/function DISPLAYWORDS() in python to read lines from a text file POEM.TXT, and
display those words, which are less than 4 characters.
ans def COUNT_BLANK_SPACES(): 3
f=open("STORY.txt",'r')
str=f.read()
x=str.split()
count=0
for i in x:
count+=1
print("Total no. blank spaces are ",count-1)
f.close()
Any other logic 3 marks
OR
def DISPLAYWORDS():
file=open(„POEM.txt','r')
line = file.read()
word = line.split()
for w in word:
if len(w)<4:
print( w)
file.close()

(½ Mark for opening the file)


(½ Mark each for reading line and/or splitting)
(½ Mark each for loop amd checking condition)
(½ Mark for printing word)

28 (a) ConsiderthefollowingtablesGAMES.GiveoutputsforSQLqueries(i)to(iv). 3
Table:GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 CaromBoard 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 TableTennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 LawnTennis 4 25000 19-Mar-2004

(i) SELECTCOUNT(DISTINCTNumber)FROMGAMES;
(ii) SELECTMAX(ScheduleDate),MIN(ScheduleDate)FROMGAMES;
(iii) SELECTSUM(PrizeMoney)FROMGAMES;
(iv) SELECT*FROMGAMESWHEREPrizeMoney>12000;

(b) Whatare the eligible candidate keys from the Table Games?
ans (a) 2+
i) 2 1
ii) 19-Mar-2004 12-Dec-2003
iii) 59000
iv)
GCode GameName Number PrizeMoney ScheduleDate
108 LawnTennis 4 25000 19-Mar-2004

(b)
GCode GameName
29 Write definition of a method/function DoubletheOdd( ) to add and display twice of odd values 3
from the list of Nums.
For example :
If the Nums contains [25,24,35,20,32,41]
The function should display
Twice of Odd Sum: 202
ans def DoubletheOdd( ): 3
Nums=[25,24,35,20,32,41]
s=0
for i in Nums :
if i%2!=0:
s+=i*2
print(s)

(3 marks for correct code)


30 Pramod has created a dictionary containing EMPCODE and SALARY as key value pairs of 5 Employees
of Parthivi Constructions.
Write a program, with separate user defined functions to perform the following operations:
● Push the keys (Employee code) of the dictionary into a stack, where the corresponding value (Salary) is
less than 25000.
● Pop and display the content of the stack. For example: If the sample content of the dictionary is as
follows:

EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000, "EOP4":15000, EOP5":30000}

The output from the program should be: EOP4 EOP3 EOP1
OR

Write a function POP(Arr) , where Arr is a stack implemented by a list of numbers The function returns the
value deleted from the stack.

ans EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000, "EOP4":15000,"EOP5":30000}


def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in EMP:
if EMP[k]<25000:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end="")
else:
break

OR
def POP(Arr):
if len(Arr)==0:
print(“Underflow”)
else:
L=len(Arr)
val=Arr[L-1]
print(val)
return (Arr.pop(L-1))
(Any other correct code can also be given.)
SECTIOND
31 Quick Learn University is setting up its academic blocks at Prayag Nagar and planning to set up a
network. The university has 3 academic blocks and one human resource Centre as shown in the
diagram given below:

Business Technology
Block Block

Law Block HR Centre

Centre-to-Centre distance between various blocks is as follows:


Law block to business block 40 m
Law block to technology block 80 m
Law block to HR block 105 m
Business block to technology block 30 m
Business block to HR block 35 m
Technology block to HR block 15 m
Number of computers in each of the buildings is as follows:
Law block 15
Technology block 40
HR Centre 115
Business block 25
(a) Suggest a cable layout of connection between the blocks. 1
1
(b) Suggest the most suitable place to house the server of the organization with suitable reason.
(c) Which device should be placed/ installed in each of these blocks to efficiently connect all the 1
computers within these blocks?
(d) The university is planning to link its sales counters situated in various parts of the CITY. Which 1
type of network out of LAN, MAN or WAN will be formed?
1
(e) Which network topology may be preferred between these blocks?
ans (a) Suggest a cable layout of connection between the blocks. 1

(b) Ans : HR centre because it consists of the maximum number of computers to house the 1
server.
(c) Ans: Switch/ Hub should be placed in each of these blocks. 1
1
(d) Ans : MAN
1
(e) Ans : Bus
32 (a) Find and write the output of the following python code: 2+
def Change(P ,Q=10): 3
P=P*Q
Q=Q+P
print( P,"#",Q)
return (Q)
A=5
B=10
A=Change(A)
B=Change(A,B)
print(A,"#",B)

(b)
Avni is trying to connect Python with MySQLfor her project. Help her to write the python
statement on the following:-
(i) Name the library, which should be imported to connect MySQL with Python.
(ii)Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having the arguments values as :
Host name :192.168.11.111
User : root
Password: Admin
Database : MYPROJECT
OR
(a)Find and write the output of the following python code:
def encrypt(s):
k=len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+str(i)
elif s[i].islower():
m=m+s[i].upper()
else:
m=m+'*'
print(m)
encrypt('Kvs@Hyderabad')

(b)
NotethefollowingtoestablishconnectivitybetweenPythonand MYSQL:
 Usernameismyusername
 Passwordismypassword
 ThetableexistsinaMYSQLdatabasenamedmydatabase

Writethefollowingmissingstatementstocompletethecode:
Statement 1 – to create the connection object
Statement2–tocreate the cursor object
Statement3-To execute the sql query

import mysql.connector

mydb = _____________________________ # Statement 1


mycursor = _______________ # Statement 2

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")

mycursor._________________ # Statement 3

mydb.commit()

print(mycursor.rowcount, "record inserted.")

ans (a)
50 # 60
600 # 610
60 # 610

(b)
(i) import mysql.connector
(ii) execute (<sql query >)
(iii)mysql.connector.connect(host=”192.168.11.111”,user=”root”,passwd=”Admin”,
database=”MYPROJECT”)

OR
(a)0VS*4YDERABAD
(b)
import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="myusername",
password="mypassword", database="mydatabase" ) # Statement 1
mycursor = mydb.cursor() # Statement 2
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val) # Statement 3
mydb.commit()
print(mycursor.rowcount, "record inserted.")
33 Manoj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain 5
user name and password for some entries. He has written the following code. As a programmer,
help him to successfully execute the given task.
import ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close()
# csv file reading code
def readCsvFile(): #to read data from CSV file
with open('user.csv','r') as newFile:
newFileReader=csv.______(newFile) #Line3
for row in newFileReader:
print(row)
newFile.________________ #Line4
addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()

OUTPUT___________________ #Line 5

(a) What module should be imported in #Line1 for successful execution of the program?
(b) In which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file
(e) Write the output he will obtain while executing Line5

OR
Radha Shah is a programmer, who has recently been given a task to write a python code to perform the
following CSV file operations with the help of two user defined functions/modules:

(a) . CSVOpen() : to create a CSV file called books.csv in append mode containing information of books
– Title, Author and Price.
(b). CSVRead() : to display the records from the CSV file called books.csv where the field title starts with
'R'.
She has succeeded in writing partial code and has missed out certain statements, so she has left certain
queries in comment lines.
import csv
def CSVOpen():
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try: with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()

You as an expert of Python have to provide the missing statements and other related queries based on the
following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Which statement will be used to create a csv writer object in Statement 2.
(c) Write the correct option for Statement 3 to write the names of the column headings in the CSV file,
books.csv
(d) Write statement to be used to read a csv file in Statement 4.
(e) Fill in the appropriate statement to check the field Title starting with „R‟ for Statement 5 in the above
program.
ans a) csv
b) w
c) reader()
d) close()
e) ['Frieda', 'myname@FRD']
OR
(a) a
(b) csv.writer(csvf)
(c) cw.writerow(['Title','Author','Price'])
(d) csv.reader(csvf)
(e) r[0][0]=='R‟
34 A departmental store MyStore is considering to maintain their inventory using SQL to store the
data. As a database Administrator, Abhay has decided that:
Name of the database – mystore
Name of the table –STORE
The attributes of STORE are as follows
ItemNo –numeric
ItemName – character of size 20
Scode – numeric
Quantity – numeric
Table : STORE
ItemNo ItemName Scode Quantity
2005 Sharpner Classic 23 60
2003 Ball Pen 0.25 22 50
2002 Gel Pen Premium 21` 150
2006 Gel Pen Classic 21 250
2001 Eraser Small 22 110
2004 Eraser Big 22 220
2009 Ball Pen 0.5 21 180

(a) Identify the attribute best suitable to be declared as primary key


(b) Write the query to add the row with following details
(2010,”Notebook”,23,155)
(c)
(i) Abhay wants to remove the table STORE from the database MyStore, Help Abhay in writing
the command for removing the table STORE from the database MyStore.
(ii) Now Abhay wants to display the structure of the table STORE i.e. name of the attributes and
their respective data types that he has used in the table. Write the query to display the same.
OR
(i) Abhay wants to ADD a new column price with data type as decimal. Write the query to add the
column..
(ii) Now Abhay wants to remove a column price from the table STORE. Write the query.

ans (a) ItemNo


(b) INSERT INTO STORE VALUES (2010,”Notebook”,23,155);
(c)
(i) DROP TABLE STORE;
(ii) DESCRIBE STORE;
OR
(i) Alter table STORE
add price decimal(2,1);
(ii) Alter table Store
drop price;
35 Manoj is learning to work with Binary files in Python using a process known as Pickling/de-
pickling. His teacher has given him the following incomplete code, which is creating a Binary file
namely Mydata.dat and then opens, reads and displays the content of this created file.

import____________#Statement-1

sqlist=list()

for k in range(5): sqlist.append(k*k)

fout=open(“mydata.dat”,____________) #Statement-2

_____________(sqlist,fout) #Statement-3

fout.close()

fin=open(“Mydata.dat”, “rb” )

mylist= _________________(fin) #Statement-4

fin.close()

print(mylist) 1
1
i) Which module should be imported in Statement-1.
1
ii) Which file mode to be passed to write data in file in Statement-2
iii) What should be written in Statement-3 to write data onto the file. 1
iv) Which function to be used in Statement-4 to read the data from the file.
ans i) pickle 1
ii) wb 1
iii) pickle.dump()
1
iv) pickle.load()
1
KENDRIYA VIDYALAYA SANGATHAN, JABALPUR REGION
FIRST PREBOARD EXAMINATION (2022-23)
CLASS - XII
SUBJECT- Computer Science (083)
Max Marks : 70 Time : 3 Hrs

General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given
in Q34 against part iii only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1 Find the invalid identifier from the following 1
a) Marks@12 b) string_12 c)_bonus d)First_Name
2 Identify the valid declaration of Rec: 1
Rec=(1,‟Ashoka",50000)
a) List b) Tuple c)String d) Dictionary
3 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80) which of 1
the following is incorrect?
a) print(Tup[1]) b) Tup[2] = 90
c) print(min(Tup)) d) print(len(Tup))
4 The correct output of the given expression is: 1
True and not False or False
(a) False (b) True (c) None (d) Null
5 t1=(2,3,4,5,6) 1
print(t1.index(4))
output is
(a) 4 (b) 5 (c) 6 (d) 2
6 Which of the following modes is used to open a binary file for writing 1
(a) b (b) rb+ (c) wb (d) rb
7 Fill in the blank: 1
The ________ command is used in a WHERE clause to search for a
specified pattern in a column.
(a) match (b) similar (c) like (d) pattern
8 Which of the following commands is used to modify a table in SQL? 1
(a) MODIFY TABLE (b) DROP TABLE
(c) CHANGE TABLE (d) ALTER TABLE
9 Which of the following statement(s) would give an error after 1
executing the following code?
x= int("Enter the Value of x:")) #Statement 1
for y in range[0,21]: #Statement 2
if x==y: #Statement 3
print (x+y) #Statement 4
else: #Statement 5
print (x-y) # Statement 6
(a) Statement 4 (b) Statement 5
(c) Statement 4 & 6 (d) Statement 1 & 2
10 Fill in the blank: 1
For each attribute of a relation, there is a set of permitted values,
called the _______of that attribute.
(a) cardinality (b) degree (c) domain (d) tuple
11 What is the significance of the tell() method? 1
(a) tells the path of the file.
(b) tells the current position of the file pointer within the file.
(c) tells the end position within the file.
(d) checks the existence of a file at the desired location.
12 Fill in the blank: 1
The SELECT statement when combined with __________ clause,
returns records in sorted order.
(a) SORT (b) ARRANGE (c) ORDER BY (d) SEQUENCE
13 Fill in the blank: 1
The _______ is a mail protocol used to retrieve mail from a remote
server to a local email client.
(a) VoIP (b) FTP (c) PPP (d) HTTP
14 Evaluate the following Python expression 1
print(12*(3%4)//2+6)
(a)12 (b)24 (c) 10 (d) 14
15 In SQL, the aggregate function used to calculate and display the 1
average of numeric values in an attribute of a relation is:
(a) sum() (b) total() (c) count() (d) avg()
16 The name of the module used to establish a connection between 1
Python and SQL database is-
(a) mysql-connect (b) mysql-connector
(c) mysql-interface (d) mysql-conn
Q17 and 18 are ASSERTION AND REASONING based questions.
Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A):- The default arguments can be skipped in the function 1
call.
Reasoning (R):- The function argument will take the default values
even if the values are supplied in the function call
18 Assertion (A):- If a text file already containing some text is opened in 1
write mode the previous contents are overwritten.
Reasoning (R):- When a file is opened in write mode the file pointer is
present at the beginning position of the file
SECTION B
19 Aarti has written a code to input an integer and check whether it is 2
even or odd. The code has errors. Rewrite the code after removing all
the syntactical errors, underlining each correction:
checkval def():
x = input("Enter a number")
if x % 2 == 0
print (x, "is even")
else;
print (x, "is odd")
20 What is the difference between hub and switch? Which is more 2
preferable in a large network of computers and why?
OR
Differentiate between WAN and MAN. Also give an example of WAN.
21 (a) Given is a Python string declaration: 2
str="Kendriya Vidyalaya Sangathan"
Write the output of: print(str[9:17])
(b) Write the output of the code given below:
lst1 = [10, 15, 20, 25, 30]
lst1.insert( 3, 4)
lst1.insert( 2, 3)
print (lst1[-5])
22 What are constraints in SQL? Give two examples. 2
23 (a) Write the full forms of the following: 2
(i) TCP (ii) VPN
(b) What is the use of FTP?
24 Predict the output of the Python code given below: 2
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)
OR
Predict the output of the Python code given below:
a=20
def call():
global a
b=20
a=a+b
return a
print(a)
call()
print(a)
25 What are aggregate functions in MySql? Give their names along with 2
their use.
OR
List various DDL and DML commands available in MySql
SECTION C
26 (a) Consider the following tables – EMPLOYEES AND 1
DEPARTMENT
What will be the output of the following statement?
SELECT ENAME, DNAME FROM EMPLOYEES, DEPARTMENT
WHERE EMPLOYEE.DNO=DEPARTMENT.DNO;
(b) Write the output of the queries (i) to (iv) based on the tables given 2
below:

i) SELECT ITEM_NAME, MAX(PRICE), COUNT(*) FROM ITEM


GROUP BY ITEM_NAME;
ii) SELECT CNAME, MANUFACTURER FROM ITEM, CUSTOMER
WHERE ITEM.ID=CUSTOMER.ID;
iii) SELECT ITEM_NAME, PRICE*100 FROM ITEM WHERE
MANUFACTURER="ABC";
(iv) SELECT DISTINCT CITY FROM CUSTOMER;
27 Write a function in python to count the number of lines in a text file 3
‘Country.txt’ which are starting with an alphabet ‘W’ or ‘H’.
For example, If the file contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
OR
Write a user defined function to display the total number of words
present in a text file 'Quotes.txt'
For example if the file contents are as follows:
Living a life you can be proud of doing your best Spending your time
with people and activities that are important to you Standing up for
things that are right even when it’s hard Becoming the best version of
you.
The countwords() function should display the output as:
Total number of words : 40
28 (a) Write the outputs of the SQL queries (i) to (iv) based on the 2
relations SCHOOL and ADMIN given below:

(i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP


BY SUBJECT;
(ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN
WHERE DESIGNATION = ‘COORDINATOR’ AND
SCHOOL.CODE=ADMIN.CODE;
(iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
(iv) SELECT MAX(PERIODS) FROM SCHOOL;
1
(b) Write the command to view the structure of a table SCHOOL
29 Write a function in python named SwapHalfList(Array), which accepts 3
a list Array of numbers and swaps the elements of 1st Half of the list
with the 2nd Half of the list, ONLY if the sum of 1st Half is greater
than 2nd Half of the list.
Sample Input Data of the list
Array= [ 100, 200, 300, 40, 50, 60],
Output Array = [40, 50, 60, 100, 200, 300]
30 Write a function in Python PushBook(Book) to add a new book entry 3
as book_no and book_title in the list of Books , considering it to act as
push operations of the Stack data structure.
OR
Write a function in Python PopBook(Book), where Book is a stack
implemented by a list of books. The function returns the value deleted
from the stack.
SECTION D
31 Rehaana Medicos Center has set up its new center in Dubai. It has
four
buildings as shown in the diagram given below:

Distances between various buildings are as follows:

No of Computers

As a network expert, provide the best possible answer for the


1
following
queries: 1
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server 1
of
1
this organization.
iii) Suggest the placement of the Repeater device with justification. 1
iv) Suggest a system (hardware/software) to prevent unauthorized
access to or from the network.
(v) Suggest the placement of the Hub/ Switch with justification.
32 (a) Write the output of the code given below: 2
x = 50
def func():
global x
print('x is', x)
x = 20
print('Changed global+local x to', x)
func()
(b) The code given below inserts the following record in the table 3
Book:
B_No – integer
B_Name – string
B_Author – string
Price – Decimal
Note the following to establish connectivity between Python and
MYSQL:
▪ Username is root
▪ Password is tiger
▪ The table exists in a MYSQL database named Library.

The details (B_No, B_Name, B_Author and Price) are to be accepted


from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the
table Book.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
conn=mysql.connect(host="localhost", user="root",
password="tiger", database="Library")
mycursor=_________________ #Statement 1
B_No=int(input("Enter Book Number : "))
B_Name=input("Enter Book Name : ")
B_Author=input("Enter Author : ")
Price=float(input("Enter Price : "))
sql="insert into Book values({},'{}','{}',{})".format(B_No, B_Name,
B_Author, Price)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
conn.close()

OR
(a) Predict the output of the code given below:
def convert(Old):
l=len(Old)
New=" "
for i in range(0,1):
if Old[i].isupper():
New=New+Old[i].lower()
elif Old[i].islower():
New=New+Old[i].upper()
elif Old[i].isdigit():
New=New+"*"
else:
New=New+"%"
return New
Older="InDIa@2022"
Newer=Convert(Older)
print("New String is: ", Newer)
(b) The code given below reads and fetches all the records from EMP
table having salary more than 25000.
empno - integer,
ename- string and
salary- integer.
Note the following to establish connectivity between Python and
MYSQL:
▪ Username is root
▪ Password is tiger
▪ The table exists in a MYSQL database named company.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those
employees having salary more than 25000.
Statement 3- to read the complete result of the query (records whose
salary is more than 25000) into the object named data, from the table
EMP in the database.

import mysql.connector as mysql


def sql_data():
conn=mysql.connect(host="localhost", user="root", password=
"tiger", database="company")
mycursor=______________ #Statement 1
print("Employees with salary more than 25000 are : ")
try:
______________________________ #Statement 2
resultset=_____________________ #Statement 3
for row in resultset:
print(row)
except:
print("Error: unable to fetch data")
conn.close()
33 A binary file “Book.dat” has structure [BookNo, Book_Name, Author, 5
Price].
i. Write a user defined function CreateFile() to input data for a record
and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of books by
the given Author are stored in the binary file “Book.dat”

OR
A binary file “STUDENT.DAT” has structure (admission_number,
Name, Percentage). Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number
of students scoring above 75%
SECTION E
34 Modern Public School is maintaining fees records of students. The
database administrator Aman decided that-
• Name of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno - numeric
Name – character of size 20
Class - character of size 20
Fee – Numeric
Qtr – Numeric
Answer any four from the following questions:
(i) Identify the attribute best suitable to be declared as a primary key 1
(ii) What is the degree of the table. 1
(iii) Write the statements to:
a. Insert the following record into the table 2
Rollno-1201, Name-Akshay, Class-12th, Fee-350, Qtr-2
b. Increase the second quarter fee of class 12th students by 50

OR (Option for part iii only)


a. Delete the record of student with Rollno-1212
b. Aman wants to add a new column to the Fees table,
Which command will he use from the following:
a) CREATE
b) ALTER
c) SHOW
d) DESCRIBE
35 Vijay of class 12 is writing a program to create a CSV file
“mydata.csv” which will contain user name and password for some
entries. He has written the following code. As a programmer, help him
to successfully execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # write data into the CSV
file
f=open(' mydata.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
def readCsvFile(): # read data from CSV file
with open('mydata.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Vijay”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”) 1
readCsvFile()
(i) Give Name of the module he should import in Line 1. 1
(ii) In which mode, Vijay should open the file to add data into the file in
Line2. 2
(iii) Complete the Line 3 to read the data from csv file and Line 4 to
close the file.
केंद्रीय विद्यालय संगठन कोलकाता संभाग
KENDRIYA VIDYALYA SANAGATHAN , KOLKATA REGION

पूिव बोर्व परीक्षा / PRE-BOARD EXAM– 1


MARKING SCHEME (SET-1)
कक्षा /CLASS - XII अधिकतम अंक / MAX. MARKS: 70

विषय / SUBJECT : COMPUTER SCIENCE समय /TIME : 3 घंटे / HRS.

प्रश्न पत्र कोड / Q. P. CODE : CS/PB1/22-01

_________________________________________________________________________________________

SECTION A
1. State True or False : 1
Python does not allows same variable to hold different data literals / data types.

Ans : False
2. Which of the following datatype in python is used to represent any real number : 1
(a) int , (b) complex , ( c ) float , (d ) bool

( c ) float
3. 1
Given the following list
place=[ (“State” , ”Sikkim”), (“Population”, ”8 Lakh”) ]
which of the following method will turn the above list place into something like
{ “State” : “Sikkim” , “Population” : “8 Lakh” }
when applied over it :
a. dictionary( )
b. to_dict( )
c. dict( )
d. Items( )

c. dict( )

4. Consider the given Expression : 1


5 == True and not 0 or False
Which of the following will be the correct output if the given expression is evaluated?
a. True
b. False
c. NONE
d. NULL

b. False

5. Select the correct output of the code : 1


n = "Post on Twitter is trending"
q = n.split('t')
print( q[0]+q[2]+q[3]+q[4][1:] )

a. Pos on witter is rending


b. Pos on Twitter is ending
c. Poser witter is ending
d. Poser is ending

d) Poser is ending
6. Which of the following mode in file opening statement does not overwrites the any previous 1
content of the file ?
a. w+ b. r+ c. a+ d. None of the above

c. a+

7. ___________ command is used to a remove a tuple or many tuple(s) from a table / relation 1
in SQL

(a) drop (b)delete (c) remove (d) alter

b. delete
8. Which of the following commands will remove a particular table’s schema along with its data 1
, contained in a MySQL database?
a. DROP DATABASE
b. ALTER TABLE
c. DELETE FROM TABLE
d. DROP TABLE

c. DROP TABLE
9. Which of the following statement(s) would give an error after executing the following code? 1
EM = “Blue Tick will cost $8” # Statement 1
print( EM) # Statement 2
ME = “Nothing costs more than Truth” # Statement 3
EM *= 2 # Statement 4
EM [-1: -3 : -1] += ME[ : 7] # Statement 5

a. Statement 3
b. Statement 4
c. Statement 5
d. Statement 4 and 5

c.Satement 5
10. ……………………is an attribute, which is not a primary key of a table but has a capability of 1
becoming a primary key.

a. Primary Key
b. Foreign Key
c. Candidate Key
d. Alternate Key

c.Candidate Key
11. The seek( 8 ) if applied to a text file stream object moves the read cursor/ pointer : 1

a. 8 characters backwards from its current position


b. 8 characters backward from the end of the file
c. 8 characters forward from its current position
d. 8 characters forwarded from the beginning of the file

d. 8 characters forwarded from the beginning of the file

12. To restrict repeated values from being entered under a column of table, while creating the 1
table in MySQL we take help of which of the following :

a. DESCRIBE
b. NULL
c. PRIMARY KEY
d. DISTINCT

b. PRIMARY KEY
13 ……………………is a communication methodology designed to establish a direct and dedicated 1
communication between an internet user and his/her ISP.

(a) VoIP (b) SMTP (c) PPP (d)HTTP

c. PPP

14. What will the following expression be evaluated to in Python? 1


print( ( - 33 // 13) * (35 % -2)* 15/3)

a. 10.0
b. -15.0
c. 15.0
d. -10.0
c. 15.0
15. Which function is not an aggregate function ? 1

a. sum()
b. total()
c. count()
d. avg()

b. total( )
16. Which of the following method is needed to create an object using whose method a query 1
is executed from python’s front end connected to a mysql database.
a. cursor( )
b. execute( )
c. Connect( )
d. fetchall( )

a. cursor( )
Q17 and 18 are ASSERTION AND REASONING based questions.
Mark the correct choice as
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
17. Assertion(A):Key word arguments are related to the function calls 1

Reason(R): When you use keyword arguments in a function call, the caller identifies the
arguments by the parameter name

i. Both A and R are true and R is the correct explanation for A

18. Assertion (A): - The acronym for a CSV File is “ Comma Separated Value” 1

Reasoning (R):- Since the seprator symbols between data elements with a line should
always be a comma hence the name CSV originated.

iii. A is True but R is False


SECTION B
19. Mithilesh has written a code to input a number and evaluate its factorial and then finally 2
print the result in the format : “The factorial of the <number> is <factorial value>” His code
is having errors. Rewrite the correct code and underline the corrections made.

f=0
num = input("Enter a number whose factorial you want to evaluate :")
n = num
while num > 1:
f = f * num
num -= 1
else:
print("The factorial of : ", n , "is" , f)

Ans :

1. f =1 # f is wrongly initialized to 0
2. int( ) must be used with input( )
3. else part of while should be properly indented
4. print("The factorial of : ", n , "is" , f)
Hence the correct code will be :

f=1
num = int(input("Enter a number whose factorial you want to evaluate :"))
org_num = num
while num > 1:
f = f * num
num -= 1
else:
print("The factorial of : ", org_num , "is" , f)

20. 2
Write any one point of difference between
i. Circuit Switching and Packet Switching.
ii. Co-axial cable and Fiber – optic cable
OR
Write two points of difference between Bus and Star Topologies.

1 marks each for any two correct differences

21. a. Given is a Python string declaration: 2


Wish = "## Wishing All Happy Diwali @#$"
Write the output of Wish[ -6 : : -6 ]

Ans : lyli#

b. Write the output of the code given below :


Emp = { "SMITH":45000 , "CLARK":20000 }
Emp["HAPPY"] = 23000
Emp["SMITH"] = 14000
print( Emp.values() )

Ans : dict_values([14000, 20000, 23000]) or [14000,20000,23000]


22. Explain the use of ‘Foreign Key’ for performing table Joins, giving a suitable example to 2
support your answer.
1 mark to make role of Foreign Key clear in joining tables + 1 marks for example

23. a. Write the full form of : 2


 HTML
 VoIP
b. What do you mean by a URL ?

Ans a. HTML – HYPER TEXT MARKUP LANGUALGE (½+½)


VoIP – VOICE OVER INTERNET PROTOCOL
b. URL – UNIFORM RESOURCE LOCATER or Any correct definition award 1 mark.
24. def Compy(N1,N2=10): 2
return N1 > N2

NUM= [10,23,14,54,32]
for VAR in range (4,0,-1):
A=NUM[VAR]
B=NUM[VAR-1]
if VAR > len(NUM)//2:
print(Compy(A,B),'#', end=' ')
else:
print(Compy(B),'%',end=' ')

Ans : False # True # True % False %

OR

tuple1 = ( [7,6], [4,4], [5,9] , [3,4] , [5,5] , [6,2] , [8,4])


listy = list( tuple1)
new_list = list()
for elem in listy :
tot = 0
for value in elem:
tot += value
if elem.count(value) == 2:
new_list.append(value)
tot = 0
else:
print( tuple(new_list) )

Ans : ( 4,4,5,5)
25. Differentiate between ‘WHERE’ clause and ‘HAVING’ clause in MySQL with appropriate 2
example.
OR

Differentiate between DELETE and DROP keywords used in MySQL,giving suitable example
for each
Correct difference one mark
Correct example one mark
SECTION C
26. (a) Consider the following tables – Bank_Account and Branch: 1+2
BANK_ACCOUNT
E_CODE NAME
E01 ASHISH
E02 SURESH

BRANCH
E_CODE LOCATION
E05 MUMBAI

What will be the output of the following statement?


SELECT * FROM Bank_Account, Branch;

Ans :
+--------+--------+--------+----------+
| e_code | name | e_code | location |
+--------+--------+--------+-----------+
| E01 | ASHISH | E05 | MUMBAI |
| E02 | SURESH | E05 | MUMBAI |
+--------+--------+--------+------------+
(1 mark for correct output)

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

TEACHER
TCODE TNAME SUBJECT SEX SALARY
5467 Narendra Kumar Computer Science M 70000
6754 Jay Prakash Accountancy M Null
8976 Ajay Kumar Chemistry M 65000
5674 Jhuma Nath English F 55000
8756 Divya Bothra Computer Science F 75000
6574 Priyam Kundu Physics M Null
3425 Dinesh Verma Economics M 71000

i) SELECT DISTINCT(SUBJECT) FROM TEACHER WHERE SALARY IS NOT NULL;


ii) SELECT SUBJECT , COUNT(*) AS TOT_FACUL FROM TEACHER GROUP BY SUBJECT
HAVING TOT_FACUL > 1
iii) SELECT TNAME FROM TEACHER WHERE SEX = ‘M’ AND
SALARY >= 70000 ORDER BY TCODE
iv) SELECT MAX(SALARY) FROM TEACHER WHERE TCODE IN (5467,8976,3425) AND
SUBJECT LIKE ‘C%’

Ans:I)
SUBJECT
Computer Science
Chemistry
English
Economics

II)

SUBJECT TOTA_FACUL
Computer Science 2

III)

TNAME
Dinesh Verma
Narendra Kumar

IV)
MAX(SALARY)
70000
( ½ mark for the correct output)
27. Write a function COUNTLINES( ) which reads a text file STORY.TXT and then count and 3
display the number of the lines which starts and ends with same letter irrespective of its
case . For example if the content of the text file STORY.TXT is :

The person has a sent a lovely tweet


Boy standing at station is very disturbed
Even when there is no light we can see
How lovely is the situation

The expected output is :

The Number of lines starting with same letter is 2

Ans :
def COUNTLINES():
fin = open("Story.txt", 'r')
lines = fin.readlines()
count = 0
for line in lines:
if line[0].lower() == line[-1].lower():
count+=1
else:
print("The Number of lines starting with same letter is",count)
fin.close()

( ½ mark for correctly opening and closing the file ½ for readlines() , ½ mark for correct loop
½ for correct if statement, ½ mark for correctly incrementing count , ½ mark for displaying
the correct output)
OR

Write a function VOWEL_WORDS which reads a text file TESTFILE.TXT and then count and
display the number of words starting with vowels ‘a’ or ‘u’ (including capital cases A and U
too)
For example is the text in the file TESTFILE.txt is :

The train from Andaman has earned the name ‘Floating Train’. What is so unique about this
train to receive such a name?

The expected output is :

The Number of words starting with letter ‘a’ is : 3


The Number of words starting with letter ‘u’ is : 1

Ans :
def VOWEL_WORDS():
fin = open("TESTFILE.TXT" , 'r')
content = fin.read()
words = content.split()
acount,ucount = 0,0
for word in words:
if word[0] in "aA":
acount+=1
if word[0] in "uU":
ucount+=1
else:
print("The Number of words starting with letter ‘a’ is :",acount)
print("The Number of words starting with letter ‘u’ is :",ucount)

VOWEL_WORDS()

(½ mark for correctly opening and closing the file, ½ for readlines() , ½ mark for correct
loops, ½ for correct if statement, ½ mark for correctly incrementing counts, ½ mark for
displaying the correct output)
Note: Any other relevant and correct code may be marked

28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations Event and 3
COMPANY given below:
Table : Event
EventId EventName Date Organizer Budget
101 Wedding 26/10/2019 1004 700000
102 Birthday Bash 05/11/2019 1002 70000
103 Engagement 13/11/2019 1004 200000
104 Wedding 01/12/2019 1003 800000
105 Farewell 25/11/2019 1001 20000
Table : Company
OrganizerId Name Phone
1001 Peter 9745684122
1002 Henry 9468731216
1003 Smith 9357861542
1004 Fred 9168734567

I) SELECT Organizer, min(date) FROM Event GROUP BY Organizer;


ii) SELECT MAX(Date),MIN(Date) FROM Event;
iii) SELECT EventName, Name, Phone FROM Event , Company WHERE Organizer =
OrganizerId AND Budget<100000;
iv) SELECT Name, Date FROM Event, Company WHERE Phone like ‘%5_2’ AND Organizer =
OrganizerId;

(b) Write a command to view names of all database in MySQL server.

Ans : (a) I)
Organizer Min(date)
1004 26/10/2019
1002 05/11/2019
1003 01/12/2019
1001 25/11/2019
( ½ mark for the correct output)
(ii)
Max(date) Min(date)
01/12/2019 26/10/2019
( ½ mark for the correct output)
iii)
EventName Name Phone
Birthday Bash Henry 9468731216
Farewell Peter 9745684122
( ½ mark for the correct output)
iv)
Name Date
Smith 01/12/2019
( ½ x 4 = 2)

(b) SHOW DATABASES ( 1 mark )

29. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the 3
function. The function returns another list named ‘indexList’ that stores the indices of all
Elements of L which has a even unit place digit.
For example:
If L contains [12,4,15,11,9,56]
The indexList will have - [0,1,5]

def INDEX_LIST(L):
indexList = [ ]
for i in range(0,len(L)):
if (L[i]%10)%2 == 0:
indexList.append(i)
else:
return indexList

(½ mark for correct function header, 1 mark for correct loop , 1 mark for correct if
statement, ½ mark for return statement)
Note: Any other relevant and correct code may be marked

30. A dictionary contains records of a tourist place like : 3


Tour_dict = { ‘Name’: ‘Goa’ , ‘PeakSeason’ : ‘December’ , ‘Budget’ : 15000 ,
‘Famous’:’Beaches’}
Write the following user defined functions to perform given operations on the stack named
‘tour’:
(i) Push_tour( Tour_dict) – To Push a list containing values for Name and PeakSeason where
value of budget is less than 10000 into the tour stack

(ii) Pop_tour() – To Pop the list objects from the stack and display them. Also, display “No
more tours” when there are no elements in the stack.

For example if the following dictionaries are passed to Push_tour( ) function in the following
sequence:
{ ‘Name’: ‘Goa’ , ‘PeakSeason’ : ‘December’ , ‘Budget’ : 15000 , ‘Famous’:’Beaches’}
{ ‘Name’: ‘Nainital’ , ‘PeakSeason’ : ‘May’ , ‘Budget’ : 9000 , ‘Famous’:’Nature’}
{ ‘Name’: ‘Sikkim’ , ‘PeakSeason’ : ‘May’ , ‘Budget’ : 9500 , ‘Famous’:’Mountains’}
{ ‘Name’: ‘Kerala’ , ‘PeakSeason’ : ‘November’ , ‘Budget’ : 15000 , ‘Famous’:’Back Waters’}
{ ‘Name’: ‘Orissa’ , ‘PeakSeason’ : ‘January’ , ‘Budget’ : 8000 , ‘Famous’:’Temples’}

Then the stack ‘tour’ will contain :


[ ‘Orrisa’ , ‘January’]
[‘Sikkim’, ‘May’]
[‘Nainital’ ,’ May’]

The output produced when calling pop_tour( ) function should be :


[ ‘Orrisa’ , ‘January’]
[‘Sikkim’, ‘May’]
[‘Nainital’ ,’ May’]
No more tours

Ans :
tour = [ ]
def Push_tour( tour_dict ) :
if tour_dict[‘Budget’] < 10000 :
LstTour = [ tour_dict[‘Name’] , tour_dict[‘PeakSeason’] ]
tour.append( LstTour )

def Pop_tour( ) :
while tour != [ ] :
T = tour.pop( )
print(T)
else:
print( “No more tours”)

(1.5 marks for correct push_element() and 1.5 marks for correct pop_element())
OR

Write a function in Python, Push(stack, SItem) where , SItem is a List containing the details
of stationary items in a format like – [Name , price , Unit , Company , MRP ].
The function should push the company names of those items in the stack whose price is 10
% percent less than its MRP. Also write a function print_stack( ) to display the Item Names
and the count of Items pushed into the stack.
For example:
If following data is passed to the function:
[ ‘Pen’ , 120.00 , ‘Pcs.’ , ‘Reynolds’ , 132.00 ]
[‘Paper’, 345.00 , ‘Rim’ , ‘Camel’, 500.00]
[Eraser , 100.00 , ‘Box’ , ‘IBP’ , 110.00
The stack should contain
Eraser
Pen
The output should be:
The count of elements in the stack is 2

Ans :
def Push(stack , SItem) :
if SItem[ 1] == SItem[4] * 0.90 :
Stack.append(SItem)

def print_stack( ):
Count = len(stack)
while stack != [ ]:
Item = stack.pop()
print( Item[ 0 ] )
else:
print(“Total items present in the stack is :”, count)

(1 mark for correct function header, 1 mark for correct loop, ½ mark for correct If
statement, ½ mark for correct display of count)

SECTION D
31. “VidyaDaan” an NGO is planning to setup its new campus at Nagpur for its web-based 5
activities. The campus has four(04) UNITS as shown below:
i) Suggest an ideal cable layout for connecting the above UNITs.
ii)Suggest the most suitable place i.e. UNIT to install the server for the above
iii)
Which network device is used to connect the computers in all UNITs?
iv)Suggest the placement of Repeater in the UNITs of above network.
v) NGO is planning to connect its Regional Office at Kota, Rajasthan. Which out of
the following wired communication, will you suggest for a very high-speed
Connectivity ?
(a) Twisted Pair cable (b) Ethernet cable (c) Optical Fiber

i. Layout Admin Training

Finance Resource

ii. Admin
iii. SWITCH/HUB
iv. ADMIN & FINANCE
v. (c) Optical Fiber

32. (a) Write the output of the following code : 2+3


R=0
def change( A , B ) :
global R
A += B
R +=3
print(R , end='%')
change(10 , 2)
change(B=3 , A=2)

Ans : 3%6%
(1 mark for 3% and 1 mark for 6%)

(b) The code given below inserts the following record in the table Emp:
EmpNo – integer
EName – string
Desig – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
 Username is admin
 Password is 22admin66
 The table exists in a MYSQL database named company.
 The details (EmpNo, EName, Desig and Salary) are to be accepted from the user.
 Write the following missing statements to complete the code:
Statement 1 – to establish a connectivity to the table in the database
Statement 2 - to form the cursor object
Statement 3 – to execute the command that inserts the record in the table Student.

import mysql.connector as mysql


def sql_data():
con1=mysql.___________(host="localhost",user = “admin” , password="22admin66",
database="company") #Statement1
mycursor=_________________ #Statement 2
eno=int(input("Enter Roll Number :: "))
ename=input("Enter name :: ")
desig=input("Enter class :: ")
sal =int(input("Enter Marks :: "))
querry="insert into student values( { },'{ }',’{ }’,{ } )".format(eno,ename,desig,sal)
______________________ #Statement 3
con1.commit( )
print("Data Added successfully")

Ans : Statement 1 : Connect


Statement 2 : con1.cursor( )
Statement 3 : mycursor.execute(querry)
(1 mark for each correct answer)

OR

(a) Predict the output of the code given below:


Ans : New string is : iNdiA%****
(1 mark for first 5 characters, 1 mark for next 5 characters)

(b) The code given below reads the following record from the table named product and
displays only those records which have name starting with a specific letters :
PId – integer
PName – string
Price – integer Marks – integer
Note the following to establish connectivity between Python and MYSQL:
 Username is admin
 Password is 22admin66
 The table exists in a MYSQL database named inventory.
Write the following missing statements to complete the code: Statement 1 – to
form the cursor object
Statement 2 – to execute the query that extracts records of those products whose
name starts with a specific letters.
Statement 3- to read the complete result of the query (records whose product
name starts with a specific letters ) into the object named data, from the table
student in the database.

import mysql.connector as mysql


def sql_data( ):
con1=mysql.connect(host="localhost", user="admin”, password="22admin66",
database="inventory")
mycursor=_______________ #Statement 1
startsWith = input(“Enter the starting letter sequence to search a product : ”)
print(“Products starting with the letter sequence”,startsWith, “are :” )
_________________________ # Statement 2
data=__________________ # Statement 3
for i in data:
print( i )
print()

Ans : Statement 1 : con1.cursor( )


Statement 2 : mycursor.execute(“Select * from product where PName Like ‘%” +
startsWith +” ’) ”
Statement 3 : mycursor.fetchall( )
( 1 mark for each correct statement)

33. What is the significance of a delimiter symbol in a csv file? Write a Program in Python that 5
defines and calls the following user defined functions:
 (i) ADD_CONT() – To accept and add data of a contact to a CSV file ‘address.csv’.
Each record consists of a list with field elements as contId, cname and cmobile to
store contact id, contact name and contact number respectively.
 (ii) COUNT_CONT() – To count the number of records present in the CSV file named
‘address.csv’.

Ans: The delimiter symbol is used to separate two data elements within a line of text in the
csv file. By default it is comma but can be set to any other symbol.
import csv
def ADD_CONT( ):
fout=open("address.csv","a",newline="\n")
wr=csv.writer(fout)
contid=int(input("Enter Contact id :: "))
cname=input("Enter Contact name :: ")
cmobile=int(input("Enter mobile number :: "))
lst=[contid, cname, cmobile] ---------1/2 mark
wr.writerow(lst) ---------1/2 mark
fout.close()

def COUNT_CONT( ):
fin=open("address.csv","r",newline="\n")
data=csv.reader(fin)
d=list(data)
print(len(d))
fin.close()

ADD_CONT( )
COUNT_CONT()

(1 mark for advantage ½ mark for importing csv module , 1 ½ marks each for correct
definition of ADD_CONT( ) and COUNT_CONT( ), ½ mark for function call statements )

OR
How csv file is different from a binary file? Write a Program in Python that defines and calls
the following user defined functions:
(i) save() – To accept and add data of watches to a CSV file ‘watchdata.csv’. Each
record consists of a list with field elements as watchid, wname and wprice to store
watch id, watch name and watch price respectively.
(ii) search()- To display the records of the watch whose price is more than 6000.

Ans: CSV file stores data using ASCII Plain Text Format. Or any other correct answer award
one mark.

import csv
def save():
fout=open(“watchdata.csv","a",newline='\n')
wr=csv.writer(fout)
watchid=int(input("Enter Furniture Id :: "))
wname=input("Enter Furniture name :: ")
wprice=int(input("Enter price :: "))
FD=[ watchid, wname, wprice ]
wr.writerow(FD)
fout.close( )

def search():
fin=open(“watchdata.csv","r",newline='\n')
data=csv.reader(fin)
found=False print("The Details are")
for i in data:
if int(i[2])>6000:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()

save()
print("Now displaying")
search()

(1 mark for difference, ½ mark for importing csv module, 1 ½ marks each for correct
definition of add() and search() , ½ mark for function call statements)

SECTION E
34 Sagar a cloth merchant creates a table CLIENT with a set of records to maintain the client’s 1+1+
order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the table, he has entered 2
data of 7 clients in the table.
CLIENT
ClientName Client_ID Qtr1 Qtr2 Qtr3 Total
Suraj C120 200 300 400 900
Radha C650 190 356 220 766
Estha C430 200 100 400 700
Karuna C790 130 540 380 1050
Naresh C660 200 400 800 1400
Varun C233 400 300 220 920
Kritika C540 500 100 400 1000

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) What is the product of degree and cardinality of the above table ?
(iii) Write the statements to:Update a record present in the table with data for
Qtr2 – 200 , Qtr3 = 600 , total – sum of all Qtrs where the Client_ID is C660
OR (option for part iii only )
(iii) (a) Delete all records where total is between 500 to 900
(b) Add a column RATINGS with datatype integer whose value must lie
between 1 to 5

Ans :
(i ) Client_ID (1 mark for correct answer)
(ii) 6x7 = 42 ( 1 Marks for correct answer)
(iii) Update Client set Qtr2 = 200 , Qtr3- 600 , total = 1000 where Client_ID = 660;
( 2 marks for fully correct answer / 1 mark for partially correct
answer)
OR
(iii) (a) Delete From Client where total between 500 and 900; ( 1 mark )
(b) ALTER TABLE Client ADD Ratings int CHECK ( Ratings between 1 and 5)
( 1 mark for use of ALTER and 1 mark for CHECK Constraint )

35. Vaishanavi is a budding Python programmer. She has written a code and created a binary 4
file phonebook.dat with contactNo, name and blocked [ Y/ N ]. The file contains 10 records
as a dictionary like {‘contactNo’ : 32344455 , ‘name’: ‘kamal kant’ ,’blocked’ : “Y” }

She now wants to shift all the records which have blocked = ‘Y’ status from phonebook.dat
to a binary file blocked.dat also all records which have blocked = ‘N’ status from
phonebook.dat to unblocked.dat. She also wants to keep count and print the total number
of blocked and unblocked records. As a Python expert, help her to complete the following
code based on the requirement given above:

import _____________ #Statement 1


def shift_contact( ):
fin = open(“phonebook.dat”,’rb’)
fblock = open( ___________________ ) #Statement 2
funblock = open( ___________________ ) #Statement 3
while True :
try:
rec = __________________ # Statement 4
if rec[“blocked”] == ‘Y’:
pickle.__________________ #Statement 5
if rec[“blocked”] == ‘N’:
Pickle. ________________ # Statement 6
except:
break

(i) Which module should be imported in the program? (Statement 1)


(ii) Write the correct statement required to open a blocked.dat and unblocked.dat
binary files (Statement 2 and 3)
(iii) which statement should Vaishnavi use in statement 4 to read the data from the
binary file, phonebook.dat
(iv) which statement should Vaishnavi use in statement 5 and 6 to write data to the
blocked.dat and unblocked.dat

Ans :
(i) pickle ( 1 mark)
(ii) open( “blocked.dat” , “wb”) ; open(“unblocked.dat”,”wb”) ( ½ + ½ )
(iii) pickle.load(fin) ( 1 Mark)
(iv) pickle.dump(rec,fblock);pickle.dump(rec , funblock) ( ½ + ½ )
KENDRIYA VIDYALAYA SANGATHAN
RANCHI RAGION
COMPUTER SCINCE (083)
FIRST PRE-BOARD EXAMINATION
Class-XII
Max Marks-70 Time: 3 hrs

General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part c
only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1 Identify the invalid Python statement from the following. 1
(a) _b=1 (b) __b1= 1 (c) b_=1 (d) 1 = _b

2 Identify the valid arithmetic operator in Python from the following. 1


(a) // (b) < (c) or (d) <>

3 If Statement in Python is __ 1
(a) looping statement (b) selection statement (c) iterative (d) sequential

4 Predict the correct output of the following Python statement – 1


print(4 + 3**3/2)

(a) 8 (b) 9 (c) 8.0 (d) 17.5

5 Choose the most correct statement among the following – 1

(a) a dictionary is a sequential set of elements


(b) a dictionary is a set of key-value pairs
(c) a dictionary is a sequential collection of elements key-value pairs
(d) a dictionary is a non-sequential collection of elements

6 Consider the string state = “Jharkhand”. Identify the appropriate statement that will display the last 1
five characters of the string state?

(a) state [-5:] (b) state [4:] (c) state [:4] (d) state [:-4]

7 What will be the output of the following lines of Python code? 1

if not False:
print(10)
else:
print(20)

Page 1 of 9
(a) 10 (b) 20 (c) True (d) False

8 Consider the Python statement: f.seek(10, 1) 1


Choose the correct statement from the following:

(a) file pointer will move 10 byte in forward direction from beginning of the file
(b) file pointer will move 10 byte in forward direction from end of the file
(c) file pointer will move 10 byte in forward direction from current location
(d) file pointer will move 10 byte in backward direction from current location

9 Which of the following function returns a list datatype? 1

a) d=f.read() b) d=f.read(10) c) d=f.readline() d) d=f.readlines()

10 Identify the device on the network which is responsible for forwarding data from one device to 1
another

(a) NIC (b) Router (c) RJ45 (d) Repeater

11 A table has initially 5 columns and 8 rows. Consider the following sequence of operations 1
performed on the table –
i. 8 rows are added
ii. 2 columns are added
iii. 3 rows are deleted
iv. 1 column is added
What will be the cardinality and degree of the table at the end of above operations?

(a) 13,8 (b) 8, 13 (c) 14,5 (d) 5,8

12 Which of the following constraint is used to prevent a duplicate value in a record? 1

(a) Empty (b) check (c) primary key (d) unique

13 The structure of the table/relation can be displayed using __________ command. 1

(a) view (b) describe (c) show (d) select

14 Which of the following clause is used to remove the duplicating rows from a select statement? 1

(a) or (b) distinct (c) any (d)unique

15 How do you change the file position to an offset value from the start? 1
(a) fp.seek(offset, 0) (b) fp.seek(offset, 1) (c) fp.seek(offset, 2) (d) None of them

16 Which of the following method is used to create a connection between the MySQL database and 1
Python?
(a) connector ( ) (b) connect ( ) (c) con ( ) (d) cont ( )

Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
Page 2 of 9
17 Assertion (A): The function definition calculate(a, b, c=1,d) will give error. 1
Reason (R): All the non-default arguments must precede the default arguments.

18 Assertion (A): CSV files are used to store the data generated by various social media platforms. 1
Reason (R): CSV file can be opened with MS Excel.

SECTION - B
19 Find error in the following code(if any) and correct code by rewriting code and underline the 2
correction;‐

x= int(“Enter value of x:”)


for in range [0,10]:
if x=y
print( x + y)
else:
print( x‐y)

20 (a) 2
Find output generated by the following code:

Str = "Computer"
Str = Str[-4:]
print(Str*2)

OR
Consider the following lines of codes in Python and write the appropriate output:

student = {'rollno':1001, 'name':'Akshay', 'age':17}


student['name']= “Abhay”
print(student)

21 What do you mean by Foreign key? How it is related with Referential Integrity? 2

22 Find output generated by the following code: 2


string="aabbcc"
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string)
print(count)

23 Expand the following terms: 2


i. NIC
ii. TCP/IP
iii. POP
iv. SMTP

Page 3 of 9
24 Write one advantage and one disadvantage of each – STAR Topology and Tree Topology 2

OR

What do you mean by Guided Media? Name any three guided media?

25 Differentiate between DDL and DML? 2

OR

Write the main difference between INSERT and UPDATE Commands in SQL

SECTION - C
26 Write definition of a method/function AddOdd(VALUES) to display sum of odd values from the 3
list of VALUES

27 Define a function SHOWWORD () in python to read lines from a text file STORY.TXT, and 3
display those words, whose length is less than 5.

OR

Write a user defined function in python that displays the number of lines starting with 'H' in the file
para.txt

28 Write the outputs of the SQL queries (a) to (c) based on the relation Furniture 3

No Itemname Type Dateofstock Price Discount


1 White lotus Double Bed 23/02/2002 30000 25
2 Pink feather Baby Cot 20/01/2002 7000 20
3 Dolphin Baby Cot 19/02/2002 9500 20
4 Decent Office Table 01/01/2002 25000 30
5 Comfort Zone Double Bed 12/01/2002 25000 25
6 Donald Baby Cot 24/02/2002 6500 15
7 Royal finish Office Table 20/02/2002 18000 30
8 Royal tiger Sofa 22/02/2002 31000 30
9 Econo sitting Sofa 13/12/2001 9500 25
10 paradise Dining Table 19/02/2002 11500 25
11 Wood Comfort Double Bed 23/03/2003 25000 25
12 Old Fox Sofa 20/02/2003 17000 20
13 Micky Baby Cot 21/02/2003 7500 15

(a) SELECT Itemname FROM Furniture WHERE Type="Double Bed";


(b) SELECT MONTHNAME(Dateofstock) FROM Furniture WHERE Type="Sofa";
(c) SELECT Price*Discount FROM Furniture WHERE Dateofstock>31/12/02;
29 Consider the following table GAMES 3

GCode GameName Number PrizeMoney ScheduleDate


101 Carom Board 2 5000 23‐Jan‐2004
102 Badminton 2 12000 12‐Dec‐2003
103 Table Tennis 4 8000 14‐Feb‐2004
105 Chess 2 9000 01‐Jan‐2004
108 Lawn Tennis 4 25000 19‐Mar‐2004
Write the output for the following queries :
Page 4 of 9
(i) SELECT COUNT(DISTINCT Number) FROM GAMES;
(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;

30 Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book and delete a 3
Book from a list of Book titles, considering them to act as push and pop operations of the Stack data
structure.

OR

Mr.Ajay has created a list of elements. Help him to write a program in python with functions,
PushEl(element) and PopEl(element) to add a new element and delete an element from a List of
element Description, considering them to act as push and pop operations of the Stack data structure
. Push the element into the stack only when the element is divisible by 4.

For eg:if L=[2,5,6,8,24,32]


then stack content will be 32 24 8

SECTION - D
31 India Tech Solutions (ITS) is a professional consultancy company. The company is planning 5
to set up their new offices in India with its hub at Hyderabad. As a network adviser, you have
to understand their requirement and suggest them the best available solutions. Their queries
are mentioned as (i) to (v) below.

Physical locations of the blocks of TTC

HR BLOCK MEETING BLOCK

FINANCE BLOCK

Block to block distance (in m)


Block (From) Block (To) Distance
HR Block MEETING 110
HR Block Finance 40
MEETING Finance 80
Expected number of computers
Block Computers
HR 25
Finance 120
MEETING 90

(i)Which will be the most appropriate block, where TTC should plan to install their server?
(ii) Draw a block to block cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
(iii)What will be the best possible connectivity out of the following, you will suggest to
connect the new set up of offices in Bengalore with its London based office.
• Satellite Link
• lInfrared
Page 5 of 9
• Ethernet
(iv)Which of the following device will be suggested by you to connect each computer in each
of the buildings?
• l Switch
• l Modem
• l Gateway
(v) Company is planning to connect its offices in Hyderabad which is less than 1 km. Which
type of network will be formed?

32 Find the output of the following: 2


(a)
fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum)

(b) Consider the table 3


TRAINER
TI TNAME CITY HIREDAT SALAR
D E Y
101 SUNAINA MUMBAI 1998‐10‐15 90000
102 ANAMIKA DELHI 1994‐12‐24 80000
103 DEEPTI CHANDIGA 2001‐12‐21 82000
RG
104 MEENAKSHI DELHI 2002‐12‐25 78000
105 RICHA MUMBAI 1996‐01‐12 95000
106 MANIPRAB CHENNAI 2001‐12‐12 69000
HA

The Following program code is used to increase the salary of Trainer SUNAINA by 2000.

Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is system
The table exists in a MYSQL database named Admin.

Write the following missing statements to complete the code:


Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database

import mysql.connector as mydb


mycon = mydb.connect
(host = “localhost”,
user = “root”,
Page 6 of 9
passwd = “system”,
database = “Admin”)
cursor = _______________ #Statement 1
sql = “UPDATE TRAINER SET SALARY = SALARY + 2000
WHERE TNAME = ‘SUNAINA’”
cursor. _______________ #Statement 2
_______________ #Statement 3
mycon.close( )

OR
(a) Write the output of the following Python program code: 2
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
print(my_dict)

(b) Consider the table 3


TABLE : GRADUATE
S.N NAME STIPEN SUBJECT AVERAG DI
O D E V
1 KARAN 400 PHYSICS 68 I
2 DIWAKA 450 COMP Sc 68 I
R
3 DIVYA 300 CHEMISTR 62 I
Y
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTR 55 II
Y
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II

The Following program code is used to view the details of the graduate whose subject is
PHYSICS.

Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is system
The table exists in a MYSQL database named Admin.

Write the following missing statements to complete the code:


Statement 1 – to import the proper module
Statement 2 – to create the cursor object.
Statement 3- to Close the connection
Page 7 of 9
import ______________ as mydb #Statement 1
mycon = mydb.connect
(host = “localhost”,
user = “root”,
passwd = “system”,
database = “Admin”)
cursor = _________________ #Statement 2
sql = “SELECT * FROM GRADUATE WHERE SUBJECT = ‘PHYSICS’”
cursor. execute(sql)
mycon.commit ( )
___________________ #Statement 3
33 Sumit is a programmer who is working on a project that requires student data of a school to be 5
stored in a CSV file. Student data consists of roll no, name, class and section. He has written a
program to obtain the student data from user and write it to a CSV file. After getting errors in
the program he left five statements blank in the program as shown below. Help him to find the
answer of the following questions to find the correct code for missing statements.
#Incomplete Code
import_____ #Statement 1
fh = open(_____, _____, newline=‘ ’) #Statement 2
stuwriter = csv._____ #Statement 3
data = []
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
data.append(header)

for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
Class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_____] #Statement 4
data.append(rec)
stuwriter. _____ (data) #Statement 5
fh.close()

(i) Identify the suitable code for blank space in line marked as Statement 1.
(ii) Identify the missing code for blank space in line marked as Statement 2.
(iii) Choose the function name (with argument) that should be used in the blank space of line
marked as Statement 3.
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(v) Choose the function name that should be used in the blank space of line marked as
Statement 5 to create the desired CSV file?

OR

What are the advantages of binary file over text file? Write a Python program in Python to
search the details of the employees (name, designation and salary) whose salary is greater than
5000. The records are stored in the file emp.dat. consider each record in the file emp.dat as a
list containing name, designation and salary.

SECTION - E
34 Based on given table “DITERGENTS” answer following questions.
PID PName Price Category Manufacturer

Page 8 of 9
1 Nirma 40 Detergent Powder Nirma Group
2 Surf 80 Detergent Powder HL
3 Vim Bar 20 Disc washing Bar HL
4 Neem Face Wash 50 Face Wash Himalaya
a) Write SQL statement to display details of all the products not manufactured by HL. 1
b) Write SQL statement to display name of the detergent powder manufactured by HL. 1
c) Write SQL statement to display the name of the Product whose price is more than 0.5 2
hundred.

OR
c) Write SQL statement to display name of all such Product which start with letter ‘N’

35 Arun is a class XII student of computer science. The CCA in-charge of his school wants to 1+1+2
display the words form a text files which are less than 4 characters. With the help of his
computer teacher Arun has developed a method/function FindWords() for him in python
which read lines from a text file Thoughts. TXT, and display those words, which are lesser
than 4 characters. His teachers kept few blanks in between the code and asked him to fill the
blanks so that the code will run to find desired result. Do the needful with the following
python code.

def FindWords():
c=0
file=open(‘NewsLetter.TXT’, ‘_____’) #Statement-1
line = file._____ #Statement-2
word = _____ #Statement-3
for c in word:
if _____: #Statement-4
print(c)
_________ #Statement-5
FindWords()

(i) Write mode of opening the file in statement-1?


(ii) Fill in the blank in statement-2 to read the data from the file.
(iii) Fill in the blank in statement-3 to read data word by word
(iv) Fill in the blank in statement-4, which display the word having lesser than 4 characters

OR (Only for iii and iv above)


(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the file?

Page 9 of 9
KENDRIYA VIDYALAYA SANGATHAN
RANCHI RAGION
FIRST PREBOARD EXAMINATION
COMPUTER SCIENCE (083)
CLASS XII
MAX MARKS-70 TIME: 3 hrs
MARKING ACHEME
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part c
only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1 Identify the invalid Python statement from the following. 1
(a) _b=1 (b) __b1= 1 (c) b_=1 (d) 1 = _b

Ans – (d) 1 = _b
2 Identify the valid arithmetic operator in Python from the following. 1
(a) // (b) < (c) or (d) <>

Ans – (a) // floor division


3 If Statement in Python is __ 1
(a) looping statement (b) selection statement (c) iterative (d) sequential

Ans – (b) selection statement


4 Predict the correct output of the following Python statement – 1
print(4 + 3**3/2)

(a) 8 (b) 9 (c) 8.0 (d) 17.5

Ans – (d) 17.5


5 Choose the most correct statement among the following – 1

(a) a dictionary is a sequential set of elements


(b) a dictionary is a set of key-value pairs
(c) a dictionary is a sequential collection of elements key-value pairs
(d) a dictionary is a non-sequential collection of elements

Ans – (b) a dictionary is a set of key-value pairs


6 Consider the string state = “Jharkhand”. Identify the appropriate statement that will display the last 1
five characters of the string state?

(a) state [-5:] (b) state [4:] (c) state [:4] (d) state [:-4]

Ans – (a) state [-5:]


7 What will be the output of the following lines of Python code? 1
Page 1 of 13
if not False:
print(10)
else:
print(20)

(a) 10 (b) 20 (c) True (d) False

Ans – (a) 10
8 Consider the Python statement: f.seek(10, 1) 1
Choose the correct statement from the following:

(a) file pointer will move 10 byte in forward direction from beginning of the file
(b) file pointer will move 10 byte in forward direction from end of the file
(c) file pointer will move 10 byte in forward direction from current location
(d) file pointer will move 10 byte in backward direction from current location

Ans: (c) file pointer will move 10 byte in forward direction from current location
9 Which of the following function returns a list datatype? 1

a) d=f.read() b) d=f.read(10) c) d=f.readline() d) d=f.readlines()

Ans: d) d=f.readlines()
10 Identify the device on the network which is responsible for forwarding data from one device to 1
another

(a) NIC (b) Router (c) RJ45 (d) Repeater

Ans: (b) Router


11 A table has initially 5 columns and 8 rows. Consider the following sequence of operations 1
performed on the table –
i. 8 rows are added
ii. 2 columns are added
iii. 3 rows are deleted
iv. 1 column is added
What will be the cardinality and degree of the table at the end of above operations?

(a) 13,8 (b) 8, 13 (c) 14,5 (d) 5,8

Ans: (a) 13,8


12 Which of the following constraint is used to prevent a duplicate value in a record? 1

(a) Empty (b) check (c) primary key (d) unique

Ans: (d) unique


13 The structure of the table/relation can be displayed using __________ command. 1

(a) view (b) describe (c) show (d) select

Ans: (b) describe


14 Which of the following clause is used to remove the duplicating rows from a select statement? 1

(a) or (b) distinct (c) any (d)unique


Page 2 of 13
Ans: (b) distinct
15 How do you change the file position to an offset value from the start? 1
(a) fp.seek(offset, 0) (b) fp.seek(offset, 1) (c) fp.seek(offset, 2) (d) None of them
Ans: (a) fp.seek(offset, 0)

16 Which of the following method is used to create a connection between the MySQL database and 1
Python?

(a) connector ( ) (b) connect ( ) (c) con ( ) (d) cont ( )

Ans: (b) connect ( )


Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A): The function definition calculate(a, b, c=1,d) will give error. 1
Reason (R): All the non-default arguments must precede the default arguments.

Ans: (a) Both A and R are true and R is the correct explanation for A
18 Assertion (A): CSV files are used to store the data generated by various social media platforms. 1
Reason (R): CSV file can be opened with MS Excel.

Ans: (b) Both A and R are true and R is not the correct explanation for A
SECTION - B
19 Find error in the following code(if any) and correct code by rewriting code and underline the 2
correction;‐

x= int(“Enter value of x:”)


for in range [0,10]:
if x=y
print( x + y)
else:
print( x‐y)

Ans . Correct code:‐


x= int(input(“Enter value of x:”))
for in range (0,10):
if x==y:
print( x+y)
else:
print (x‐y)

½ mark for each correction


20 (a) 2
Find output generated by the following code:

Str = "Computer"
Str = Str[-4:]
print(Str*2)

Ans:
Page 3 of 13
uteruter
OR
Consider the following lines of codes in Python and write the appropriate output:

student = {'rollno':1001, 'name':'Akshay', 'age':17}


student['name']= “Abhay”
print(student)

Ans:
{'rollno': 1001, 'name': 'Abhay', 'age': 17}
21 What do you mean by Foreign key? How it is related with Referential Integrity? 2

Ans:
A foreign key is a non-key attribute whose value is derived from the primary key of another table.
The relationship between two tables is established with the help of foreign key. Referential integrity
is implemented on foreign key.

1 mark for explanation and 1 mark for relation with referential integrity.
22 Find output generated by the following code: 2
string="aabbcc"
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string)
print(count)

Ans:
bbcc
4
23 Expand the following terms: 2
i. NIC
ii. TCP/IP
iii. POP
iv. SMTP

Ans:
i. Network Interface Card
ii. Transmission Control Protocol/ Internet Protocol
iii. Post Office Protocol
iv. Simple Mail Transfer Protocol
½ mark for each expansion
24 Write one advantage and one disadvantage of each – STAR Topology and Tree Topology 2

½ marks for each advantage and disadvantage

OR

Page 4 of 13
What do you mean by Guided Media? Name any three guided media?

Ans –
Guided media – Physical Connection – ½ mark

Twisted pair cable, Co-axial cable, Fiber-optic cable)

½ mark for each name


25 Differentiate between DDL and DML? 2

Ans:
Data Definition Language (DDL): This is a category of SQL commands. All the commands which
are used to create, destroy, or restructure databases and tables come under this category. Examples
of DDL commands are ‐ CREATE, DROP, ALTER.
Data Manipulation Language (DML): This is a category of SQL commands. All the commands
which are used to manipulate data within tables come under this category. Examples of DML
commands are ‐ INSERT, UPDATE, DELETE.

OR

Write the main difference between INSERT and UPDATE Commands in SQL

Ans:
INSERT used to insert data into a table.
UPDATE used to update existing data within a table.

SECTION - C
26 Write definition of a method/function AddOdd(VALUES) to display sum of odd values from the 3
list of VALUES

Ans:
def AddOdd(Values):
n=len(NUMBERS)
s=0
for i in range(n):
if (i%2!=0):
s=s+NUMBERS[i]
print(s)

(2 Marks for Logic 1 mark for function definition)


27 Define a function SHOWWORD () in python to read lines from a text file STORY.TXT, and 3
display those words, whose length is less than 5.

Ans:
def SHOWWORD () :
c=0
file=open(‘STORY.TXT,'r')
line = file.read()
word = line.split()
for w in word:
if len(w)<5:
print( w)
file.close()

Page 5 of 13
(½ Mark for opening the file)
(½ Mark for reading line and/or splitting)
(½ Mark for checking condition)
(½ Mark for printing word)

OR

Write a user defined function in python that displays the number of lines starting with 'H' in the file
para.txt

Ans:
def count H( ):
f = open (“para.txt” , “r” )
lines =0
l=f. readlines ()
for i in L:
if i [0]== ‘H’:
lines +=1
print (“No. of lines are: “ , lines)

(½ Mark for opening the file)


(½ Mark for reading line and/or splitting)
(½ Mark for checking condition)
(½ Mark for printing word)
28 Write the outputs of the SQL queries (a) to (c) based on the relation Furniture 3

No Itemname Type Dateofstock Price Discount


1 White lotus Double Bed 23/02/02 30000 25
2 Pink feather Baby Cot 20/01/02 7000 20
3 Dolphin Baby Cot 19/02/02 9500 20
4 Decent Office Table 01/01/02 25000 30
5 Comfort Zone Double Bed 12/01/02 25000 25
6 Donald Baby Cot 24/02/02 6500 15
7 Royal finish Office Table 20/02/02 18000 30
8 Royal tiger Sofa 22/02/02 31000 30
9 Econo sitting Sofa 13/12/01 9500 25
10 paradise Dining Table 19/02/02 11500 25
11 Wood Comfort Double Bed 23/03/03 25000 25
12 Old Fox Sofa 20/02/03 17000 20
13 Micky Baby Cot 21/02/03 7500 15

(a) SELECT Itemname FROM Furniture WHERE Type="Double Bed";


(b) SELECT MONTHNAME(Dateofstock) FROM Furniture WHERE Type="Sofa";
(c) SELECT Price*Discount FROM Furniture WHERE Dateofstock>31/12/02;

Ans:
(a) (b) (c)
Itemane MONTHNAME(Dateofstock) Price*DIscount
White lotus February 625000
Comfort Zone December 340000
Wood Comfort February 112500

(1 mark for correct Answer)


Page 6 of 13
29 Consider the following table GAMES 3

GCode GameName Number PrizeMoney ScheduleDate


101 Carom Board 2 5000 23‐Jan‐2004
102 Badminton 2 12000 12‐Dec‐2003
103 Table Tennis 4 8000 14‐Feb‐2004
105 Chess 2 9000 01‐Jan‐2004
108 Lawn Tennis 4 25000 19‐Mar‐2004
Write the output for the following queries :
(i) SELECT COUNT(DISTINCT Number) FROM GAMES;
(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;

Ans:

(i) 2
(ii) 19‐Mar‐2004 12‐Dec‐2003
(iii)59000

30 Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book and delete a 3
Book from a list of Book titles, considering them to act as push and pop operations of the Stack data
structure.

Ans:
def PushOn(Book):
a=input(“enter book title :”)
Book.append(a)

def Pop(Book):
if (Book = =[ ]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()

OR

Mr.Ajay has created a list of elements. Help him to write a program in python with functions,
PushEl(element) and PopEl(element) to add a new element and delete an element from a List of
element Description, considering them to act as push and pop operations of the Stack data structure
. Push the element into the stack only when the element is divisible by 4.

For eg:if L=[2,5,6,8,24,32]


then stack content will be 32 24 8

Ans:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSHEl(S,N):
S.append(N)
def POPEl(S):
if S!=[]:
return S.pop()
else:
Page 7 of 13
return None
ST=[]
for k in N:
if k%4==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else: break

SECTION - D
31 India Tech Solutions (ITS) is a professional consultancy company. The company is planning 5
to set up their new offices in India with its hub at Hyderabad. As a network adviser, you have
to understand their requirement and suggest them the best available solutions. Their queries
are mentioned as (i) to (v) below.

Physical locations of the blocks of TTC

HR BLOCK MEETING BLOCK

FINANCE BLOCK

Block to block distance (in m)


Block (From) Block (To) Distance
HR Block MEETING 110
HR Block Finance 40
MEETING Finance 80
Expected number of computers
Block Computers
HR 25
Finance 120
MEETING 90

(i)Which will be the most appropriate block, where TTC should plan to install their server?
(ii) Draw a block to block cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
(iii)What will be the best possible connectivity out of the following, you will suggest to
connect the new set up of offices in Bengalore with its London based office.
• Satellite Link
• lInfrared
• Ethernet
(iv)Which of the following device will be suggested by you to connect each computer in each
of the buildings?
• l Switch
• l Modem
• l Gateway
(v) Company is planning to connect its offices in Hyderabad which is less than 1 km. Which
type of network will be formed?
Page 8 of 13
Ans:
(i) TTC should install its server in finance block as it is having maximum number of
computers.
(ii) Any suitable lyout
(iii) Satellite Link.
(iv) Switch.
(v) LAN

32 Find the output of the following: 2


(a)
fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum)

Ans. Output is:


22
(b) Consider the table 3
TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998‐10‐15 90000
102 ANAMIKA DELHI 1994‐12‐24 80000
103 DEEPTI CHANDIGARG 2001‐12‐21 82000
104 MEENAKSHI DELHI 2002‐12‐25 78000
105 RICHA MUMBAI 1996‐01‐12 95000
106 MANIPRABHA CHENNAI 2001‐12‐12 69000

The Following program code is used to increase the salary of Trainer SUNAINA by 2000.

Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is system
The table exists in a MYSQL database named Admin.

Write the following missing statements to complete the code:


Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database

import mysql.connector as mydb


mycon = mydb.connect
(host = “localhost”,
user = “root”,
passwd = “system”,
Page 9 of 13
database = “Admin”)
cursor = _______________ #Statement 1
sql = “UPDATE TRAINER SET SALARY = SALARY + 2000
WHERE TNAME = ‘SUNAINA’”
cursor. _______________ #Statement 2
_______________ #Statement 3
mycon.close( )

Ans:
Statement 1 – mycon.cursor ( )
Statement 2 – execute(sql).
Statement 3- mycon.commit ( )
OR
(a) Write the output of the following Python program code: 2
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
print(my_dict)

Ans. Output is:


30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
(b) Consider the table 3
TABLE : GRADUATE
S.NO NAME STIPEND SUBJECT AVERAGE DIV

1 KARAN 400 PHYSICS 68 I


2 DIWAKAR 450 COMP Sc 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II

The Following program code is used to view the details of the graduate whose subject is
PHYSICS.

Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is system
The table exists in a MYSQL database named Admin.

Write the following missing statements to complete the code:


Statement 1 – to import the proper module
Page 10 of 13
Statement 2 – to create the cursor object.
Statement 3- to Close the connection

import ______________ as mydb #Statement 1


mycon = mydb.connect
(host = “localhost”,
user = “root”,
passwd = “system”,
database = “Admin”)
cursor = _________________ #Statement 2
sql = “SELECT * FROM GRADUATE WHERE SUBJECT = ‘PHYSICS’”
cursor. execute(sql)
mycon.commit ( )
___________________ #Statement 3

Ans:
Statement 1 – mysql.connector
Statement 2 –. mycon.cursor ( )
Statement 3- mycon.close( )
33 Sumit is a programmer who is working on a project that requires student data of a school to be 5
stored in a CSV file. Student data consists of roll no, name, class and section. He has written a
program to obtain the student data from user and write it to a CSV file. After getting errors in
the program he left five statements blank in the program as shown below. Help him to find the
answer of the following questions to find the correct code for missing statements.

#Incomplete Code
import_____ #Statement 1
fh = open(_____, _____, newline=‘ ’) #Statement 2
stuwriter = csv._____ #Statement 3
data = []
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
data.append(header)

for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
Class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_____] #Statement 4
data.append(rec)
stuwriter. _____ (data) #Statement 5
fh.close()

(i) Identify the suitable code for blank space in line marked as Statement 1.
(ii) Identify the missing code for blank space in line marked as Statement 2.
(iii) Choose the function name (with argument) that should be used in the blank space of line
marked as Statement 3.
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(v) Choose the function name that should be used in the blank space of line marked as
Statement 5 to create the desired CSV file?

Ans.
(i) csv
(ii) “Student.csv”,“w”
Page 11 of 13
(iii) writer(fh)
(iv) roll_no,name,Class,section
(v) writerows()

OR

What are the advantages of binary file over text file? Write a Python program in Python to
search the details of the employees (name, designation and salary) whose salary is greater than
5000. The records are stored in the file emp.dat. consider each record in the file emp.dat as a
list containing name, designation and salary.

Ans.
In binary file, there is no terminator for a line and the data is stored after converting it into
machine understandable binary language. A binary file stores the data in the same way as
stored in the memory. Like text file we can’t read a binary file using a text editor.
----------------- 2 marks (any suitable difference)

import pickle as p
L=[]
with open(‘emp.dat’,’rb’) as f:
L=p.load(f)
for r in L:
if r[2]>5000:
print(“name=”,r[0])
print(“designation=”,r[1])
print(“salary=”,r[2])
----------------3 marks (any suitable code)
SECTION - E
34 Based on given table “DITERGENTS” answer following questions.
PID PName Price Category Manufacturer
1 Nirma 40 Detergent Powder Nirma Group
2 Surf 80 Detergent Powder HL
3 Vim Bar 20 Disc washing Bar HL
4 Neem Face Wash 50 Face Wash Himalaya
a) Write SQL statement to display details of all the products not manufactured by HL. 1
b) Write SQL statement to display name of the detergent powder manufactured by HL. 1
c) Write SQL statement to display the name of the Product whose price is more than 0.5 2
hundred.

OR
c) Write SQL statement to display name of all such Product which start with letter
‘N’

Ans:

a) Select * from DITERGENTS where manufacturer = ‘HL’;


b) Select Pname from DITERGENTS where manufacturer != ‘HL’;
c) Select Pname from DITERGENTS where price > price/100;

or
c) Select Pname from DITERGENTS where left(pname) = ‘N’;
Page 12 of 13
35 Arun is a class XII student of computer science. The CCA in-charge of his school wants to 1+1+2
display the words form a text files which are less than 4 characters. With the help of his
computer teacher Arun has developed a method/function FindWords() for him in python
which read lines from a text file Thoughts. TXT, and display those words, which are lesser
than 4 characters. His teachers kept few blanks in between the code and asked him to fill the
blanks so that the code will run to find desired result. Do the needful with the following
python code.

def FindWords():
c=0
file=open(‘NewsLetter.TXT’, ‘_____’) #Statement-1
line = file._____ #Statement-2
word = _____ #Statement-3
for c in word:
if _____: #Statement-4
print(c)
_________ #Statement-5
FindWords()

(i) Write mode of opening the file in statement-1?


(ii) Fill in the blank in statement-2 to read the data from the file.
(iii) Fill in the blank in statement-3 to read data word by word
(iv) Fill in the blank in statement-4, which display the word having lesser than 4 characters

OR (Only for iii and iv above)


(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the file?

Ans:
(i) r
(ii) read()
(iii) line.split()
(iv) len(c)<4

OR (Only for iii and iv above)


(iii) file.close()
(iv) readline()

Page 13 of 13
SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

Learn With YK
(Better Education for Brighter Future)
SQP1/CS (083)/XII/2022-23/Full Syllabus
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35
against part C only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1. State True or False (1)
"In Python, data type of a variable depends on its value"
2. Which of the following datatype in Python supports concatenation? (1)
a) int b) float c) bool d) str
3. What will be output of the following code: (1)
d1={1:2,3:4,5:6}
d2=d1.popitem()
print(d2)

a) {1:2} b) {5:6} c) (1,2) d) (5,6)


4. Consider the given expression: (1)
(not True) and False or True
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
5. Fill in the blank: (1)
___________ command is used to add a new column in a table in SQL.
a) update b) remove c) alter d)drop
6. Which of the following mode in file opening statement generates an error if (1)
the file exists?
a) a+ b) r+ c) w+ d) None of these
7. Which of the following commands can remove all the data from a table in a (1)
MYSQL database?
a) DELETE b) DROP c) REMOVE d) ALTER
8. Fill in the blank: (1)
A candidate key, which is not the primary key of a table, is a/an _________.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 1/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

9. Select the correct output of the code: (1)


a = "Year 2022 at all the best"
a = a.split('a')
b = a[0] + "-" + a[1] + "-" + a[3]
print (b)

a) Year – 0- at All the best


b) Ye-r 2022 -ll the best
c) Year – 022- at All the best
d) Year – 0- at all the best
10. Which of the following statement(s) would give an error during execution? (1)
S=["CBSE"] # Statement 1
S+="Delhi" # Statement 2
S[0]= '@' # Statement 3
S=S+"Thank you" # Statement 4
a) Statement 1 b) Statement 2 c) Statement 3 d) Statement 4
11. The method seek() returns: (1)
a) an integer b) a file object c) a record d) None
12. Select the correct statement, with reference to SQL: (1)
a) Aggregate functions ignore NULL
b) Aggregate functions consider NULL as zero or False
c) Aggregate functions treat NULL as a blank string
d) NULL can be written as 'NULL' also.
13. Which protocol is used for sending, but can also be used for receiving e-mail? (1)
a) VoIP b) SMTP c) PPP d)HTTP
14. What will the following expression be evaluated to in Python? (1)
15.0 // 4 * 5 / 3
a) 6.25 b) 5 c) 5.0 d) 0.25
15. Which function is used to display the total number of data values (except (1)
NULL) from a column in a table?
a) sum() b) total() c) count() d) IS NOT NULL
16. In context of Python - Database connectivity, the function fetchone() is a (1)
method of which object?
a) connection b) database c) cursor d) query
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for
c) A is True but R is False
d) A is false but R is True
17. Assertion (A):- The number of actual parameters in a function call may not be (1)
equal to the number of formal parameters of the function.
Reasoning (R):- During a function call, it is optional to pass the values to
default parameters.
18. Assertion (A): A tuple can be concatenated to a list, but a list cannot be (1)
concatenated to a tuple.
Reason (R): Lists are mutable and tuples are immutable in Python.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 2/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

SECTION B
19. Mohini has written a code to input a positive integer and display all its even (2)
factors in descending order. Her code is having errors. Rewrite the correct
code and underline the corrections made.
n=input("Enter a positive integer: ")
for i in range(n):
if i%2:
if n%i==0:
print(i,end=' ')
20. Write two points of difference between twisted pair cable and optical fiber (2)
cable.
OR
Write two points of difference between radio waves and micro waves.
21. (a) Given is a Python string declaration: (1)
myexam="Russia Ukrain"
Write the output of: print(myexam[-2:2:-2])

(b) Write the output of the code given below:


d1 = {"name": "Aman", "age": 26} (1)
d2 = {27:'age','age':28}
d1.update(d2)
print(d1.values())
22. Explain the use of ‘Foreign Key’ in a Relational Database. Give an example to (2)
support your answer.
23. (a) Write the full forms of the following: (i) POP (ii) HTTPS (1)
(b) Name the protocol used for remote login. (1)
24. Predict the output of the Python code given below: (2)
def Alpha(N1,N2):
if N1>N2:
print(N1%N2)
else: print(N2//N1,'#',end=' ')
NUM=[10,23,14,54,32]
for C in range (4,0,-1):
A=NUM[C]
B=NUM[C-1]
Alpha(A,B)

OR

Predict the output of the Python code given below:


List1 = list("Examination")
List2 =List1[1:-1]
new_list = []
for i in List2:
j=List2.index(i)
if j%2==0:
List1.remove(i)
print(List1)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 3/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

25. Consider the following two commands with reference to a table, named (2)
Students, having a column named Section:
(a) Select count(Section) from Students;
(b) Select count(*) from Students;
If these two commands are producing different results,
(i) What may be the possible reason?
(ii) Which command, (a) or (b), might be giving higher value?
OR
Name the aggregate functions which work only with numeric data, and those
that work with any type of data.
SECTION C
26. (a) Consider the following tables – Bank_Account and Branch: (1)
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current

Table: Branch
ACode City
A01 Delhi
A02 Mumbai
A01 Nagpur

What will be the degree and cardinality of the Cartesian product and the
Natural join of these tables?

(b) Write the output of the queries (i) to (iv) based on the table TECH_COURSE (2)
given below:

Table: TECH_COURSE
CID CNAME FEES STARTDATE TID
C201 Animation and VFX 12000 2022-07-02 101
C202 CADD 15000 2021-11-15 NULL
C203 DCA 10000 2020-10-01 102
C204 DDTP 9000 2021-09-15 104
C205 Mob App Development 18000 2022-11-01 101
C206 Digital marketing 16000 2022-07-25 103

(i) SELECT TID FROM TECH_COURSE;


(ii) SELECT TID, sum(fees), MIN(FEES) FROM TECH_COURSE
GROUP BY TID HAVING COUNT(TID)=1;
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000
and Cname like 'D%';
(iv) SELECT MAX(FEES) FROM TECH_COURSE WHERE FEES
BETWEEN 15000 AND 17000;

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 4/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

27. Write a method SHOWLINES() in Python to read lines from text file (3)
‘TESTFILE.TXT’ and display the lines which do not contain 'ke'.

Example: If the file content is as follows:


An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.

The SHOWLINES() function should display the output as:


We all pray for everyone’s safety.
OR
Write a function RainCount() in Python, which should read the content of
a text file “TESTFILE.TXT” and then count and display the count of occurrence
of word RAIN (case-insensitive) in the file.

Example: If the file content is as follows:


It rained yesterday
It might rain today
I wish it rains tomorrow too
I love Rain

The RainCount() function should display the output as: Rain - 2


28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations (3)
Teacher and Placement given below:
Table : Teacher
T_ID Name Age Department Date_of_join Salary Gender
1 Arunan 34 Computer Sc 2019-01-10 12000 M
2 Saman 31 History 2017-03-24 20000 F
3 Randeep 32 Mathematics 2020-12-12 30000 M
4 Samira 35 History 2018-07-01 40000 F
5 Raman 42 Mathematics 2021-09-05 25000 M
6 Shyam 50 History 2019-06-27 30000 M
7 Shiv 44 Computer Sc 2019-02-25 21000 M
8 Shalakha 33 Mathematics 2018-07-31 20000 F

Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur

(i) SELECT Department, max(salary) FROM Teacher


GROUP BY Department;
(ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM
Teacher;
(iii) SELECT Name, Salary, T.Department, Place FROM
Teacher T, Placement P WHERE T.Department =
P.Department AND P.Department='History';
(iv) SELECT Name, Place FROM Teacher natural join
Placement where Gender='F';

(b) Write the command to view all the databases in an RDBMS.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 5/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

29. Write a function INDEX_LIST(S), where S is a string. The function returns (3)
a list named ‘indexList’ that stores the indices of all vowels of S.

For example: If S is "Computer", then indexList should be [1,4,6]


30. A list contains following record of a doctor: (3)
[Doc_ID, Doc_name, Phone_number, Speciality]

Write the following user defined functions to perform given operations on


the stack named "status":
(i) Push_element() - To Push an object containing Doc_ID and Doc_name
of doctors who specialize in Anesthesia to the stack.

(ii) Pop_element() - To Pop the objects from the stack and display them.
Also, display “Stack Empty” when there are no elements in the stack.

For example: If the lists of Doctors' details are:

['D01', "Gurdas", “99999999999”,"Anesthesia”]


["D02", "Julee", “8888888888”,"cardiology"]
["D03",“Murugan”,”77777777777”,”Anesthesia”]
["D04",“Ashmit”, “1010101010”,”Medicine”]

The stack should contain


['D03', 'Murugan']
['D01', 'Gurdas']

The output should be:


['D03', 'Murugan']
['D01', 'Gurdas']
Stack Empty
OR

Write a function in Python, Push(KItem), where KItem is a dictionary


containing the details of Kitchen items– {Item:price}.

The function should push the names of those items in a stack which have price
less than 100. Also display the average price of elements pushed into the
stack.

For example: If the dictionary contains the following data:


{"Spoons":116,"Knife":50,"Plates":180,"Glass":60}

The stack should contain


Glass
Knife
The output should be:
The average price of an item is 55.0

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 6/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

SECTION D
31. Total-IT Corporation, a Karnataka based IT training company, is planning to
set up training centers in various cities in next 2 years. Their first campus is
coming up in Kodagu district. At Kodagu campus, they are planning to
have 3 different blocks, one for AI, IoT and DS (Data Sciences) each. Each
block has number of computers, which are required to be connected in
a network for communication, data and resource sharing. As a network
consultant of this company, you have to suggest the best network related
solutions for them for issues/problems raised in question nos. (i) to (v),
keeping in mind the distances between various blocks/locations and other
given parameters.

Distance between various blocks/locations:


Block Distance
IT to DS 28 m
IT to IoT 55 m
DS to IoT 32 m
Kodagu Campus to Coimbatore Campus 304 km

Number of computers:
Block Number of Computers
IT 75
DS 50
IoT 80

(i) Suggest the most appropriate block/location to house the SERVER in


the Kodagu campus (out of the 3 blocks) to get the best and effective (1)
connectivity. Justify your answer.
(ii) Suggest a device/software to be installed in the Kodagu Campus to
take care of data security. (1)
(iii) Suggest the best wired medium and draw the cable layout (Block to
Block) to most efficiently connect various blocks within the Kodagu (1)
Campus.
(iv) Suggest the placement of the following devices with appropriate
reasons: a) Switch/Hub b) Router (1)
(v) Suggest a protocol that shall be needed to provide Video Conferencing
solution between Kodagu Campus and Coimbatore Campus. (1)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 7/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

32. (a) Write the output of the code given below: (2)
p=8
def sum(q,r=5):
global p
p=(r+q)**2
print(p, end= '#')
a=2; b=5; sum(b,a)
sum(r=3,q=2)

(b) The code given below accepts the roll number of a student and increases (3)
the marks of that student by 5 in the table Student. The structure of a
record of table Student is:
RollNo – integer; Name – string; Clas – integer; Marks – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is abc
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:

import mysql.connector as mysql def sql_data():


con1=mysql.connect(host="localhost",user="root",
password="abc")
mycursor= con1.cursor()
__________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
querry="update student set marks=marks+5 where
RollNo={}".format(rno)
_______________________ #Statement 2
_______________________ # Statement 3
print("Data updated successfully")

Statement 1 – to open/activate the school database.


Statement 2 – to execute the command that updates the record in the table
Student.
Statement 3- to make the updation in the database permanent
OR
(a) Predict the output of the code given below:
s="3 & Four"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'A' and s[i] <= 'Z'):
m = m +s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
m = m +s[i-1]
if (s[i].isdigit()):
m = m + s[i].lower()
else: m = m +'-'
print(m)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 8/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

(b) The code given below reads records from the table named student and
displays only those records who have marks greater than 75. The structure
of a record of table Student is:
RollNo – integer; Name – string; Clas – integer; Marks – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is abc
• The table exists in a MYSQL database named school.
• The details (RollNo, Name, Clas and Marks) are to be accepted from
the user.
Write the following missing statements to complete the code:
Statement 1 – to create the cursor object
Statement 2 – to execute the query that extracts records of those
students whose marks are greater than 75.
Statement 3 - to read the complete result of the query (records whose
marks are greater than 75) into the object named data,
from the table student in the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="abc", database="school")
mycursor= ___________ #Statement 1
print("Students with marks greater than 75 are : ")
_______________________ #Statement 2
data= _________________ #Statement 3
for i in data:
print(i)
33. (a) What is the advantage of using a csv file for permanent storage? (5)
(b) Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD() – To accept and add data of an item to a CSV file ‘furniture.csv’.
Each record consists of Fur_id, Description, Price, and Discount.
(ii) COUNTR() – To count the number of records present in ‘furniture.csv’
whose price is less than 5000.
OR
(a) Give any one point of difference between a binary file and a csv file.
(b) Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD() – To accept and add data of an item to a binary file
‘furniture.dat’. Each record of the file is a list [Fur_id,
Description, Price, and Discount]. Fur_Id and Description are
of str type, Price is of int type, and Discount is of float type.
(ii) COUNTR() – To count the number of records present in ‘furniture.dat’
whose price is less than 5000.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 9/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

SECTION E
34. Tushar is a Python programmer. He has written a code and created a binary (4)
file record.dat with employeeid, ename and salary. The file contains 10
records.

He now has to delete a record based on the employee id entered by the user.
For this purpose, he creates a temporary file, named temp.dat, to store all
the records other than the record to be deleted. If the employee id is not
found, an appropriate message should to be displayed.

As a Python expert, help him to complete the following code (by completing
statements 1, 2, 3, and 4) based on the requirement given above:

(i) Complete Statement#1 to import the required module.


(ii) Write the correct statement required to open a temporary file
named temp.dat. (#Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data
from the binary file, record.dat
(iv) What should be written in Statement 4 to write the required records
in the file temp.dat?

import ___________ #Statement 1


def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("____________","___") #Statement 2
found=False
eid=int(input("Enter employee id: "))
while True:
try:
rec= ________________ #Statement 3
if rec["Employee id"]==eid:
found=True
else:
_________________ #Statement 4
except:
break
if found==True:
print("Record deleted.")
else:
print("Employee with such id is not found")
fin.close()
fout.close()

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 10/11


SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

35. Navdeep creates a table RESULT with a set of records to maintain the marks (4)
secured by students in Sem1, Sem2, Sem3 and their division. After creation of
the table, he has entered data of 7 students in the table.
ROLL_NO SNAME SEM1 SEM2 SEM3 DIVISION
101 KARAN 366 410 402 I
102 NAMAN 300 350 325 I
103 ISHA 400 410 415 I
104 RENU 350 357 415 I
105 ARPIT 100 75 178 IV
106 SABINA 100 205 217 II
107 NEELAM 470 450 471 I

Based on the data given above answer the following questions:

(i) Can Name be a candidate key of the table? Justify your answer.
(ii) If a column is added and 3 rows are deleted from the table result, what
will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a) Insert the following record into the table
Roll_No- 108, Name- Aadit, Sem1- 470, Sem2-444, Sem3-475, Div– I.
b) Increase the SEM2 marks of the students by 3% whose Name ends with
'A'.
OR (Option for part iii only)
(iii) Write the statements to:
a) Delete the record of students securing IV division.
b) Add a column GRADE, of type char of length 3 characters to the
RESULT table.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 11/11


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

Learn With YK
(Better Education for Brighter Future)
AnsKey/SQP1/CS (083)/XII/2022-23/Full Syllabus

SECTION A
1. State True or False (1)
"In Python, data type of a variable depends on its value"
True
2. Which of the following datatype in Python supports concatenation? (1)
a) int b) float c) bool d) str
3. What will be output of the following code: (1)
d1={1:2,3:4,5:6}
d2=d1.popitem()
print(d2)
a) {1:2} b) {5:6} c) (1,2) d) (5,6)
4. Consider the given expression: (1)
(not True) and False or True
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
5. Fill in the blank: (1)
___________ command is used to add a new column in a table in SQL.
a) update b) remove c) alter d)drop
6. Which of the following mode in file opening statement generates an error if (1)
the file exists?
a) a+ b) r+ c) w+ d) None of these
7. Which of the following commands can remove all the data from a table in a (1)
MYSQL database?
a) DELETE b) DROP c) REMOVE d) ALTER
8. Fill in the blank: (1)
A candidate key, which is not the primary key of a table, is a/an _________.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key
9. Select the correct output of the code: (1)
a = "Year 2022 at all the best"
a = a.split('a')
b = a[0] + "-" + a[1] + "-" + a[3]
print (b)

a) Year – 0- at All the best


b) Ye-r 2022 -ll the best
c) Year – 022- at All the best
d) Year – 0- at all the best
10. Which of the following statement(s) would give an error during execution? (1)
S=["CBSE"] # Statement 1
S+="Delhi" # Statement 2
S[0]= '@' # Statement 3
S=S+"Thank you" # Statement 4
a) Statement 1 b) Statement 2 c) Statement 3 d) Statement 4

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 1/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

11. The method seek() returns: (1)


a) an integer b) a file object c) a record d) None
12. Select the correct statement, with reference to SQL: (1)
a) Aggregate functions ignore NULL
b) Aggregate functions consider NULL as zero or False
c) Aggregate functions treat NULL as a blank string
d) NULL can be written as 'NULL' also.
13. Which protocol is used for sending, but can also be used for receiving e-mail? (1)
a) VoIP b) SMTP c) PPP d)HTTP
14. What will the following expression be evaluated to in Python? (1)
15.0 // 4 * 5 / 3
a) 6.25 b) 5 c) 5.0 d) 0.25
15. Which function is used to display the total number of data values (except (1)
NULL) from a column in a table?
a) sum() b) total() c) count() d) IS NOT NULL
16. In context of Python - Database connectivity, the function fetchone() is a (1)
method of which object?
a) connection b) database c) cursor d) query
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for
c) A is True but R is False d) A is false but R is True
17. Assertion (A):- The number of actual parameters in a function call may not be (1)
equal to the number of formal parameters of the function.
Reasoning (R):- During a function call, it is optional to pass the values to
default parameters.
a)
18. Assertion (A): A tuple can be concatenated to a list, but a list cannot be (1)
concatenated to a tuple.
Reason (R): Lists are mutable and tuples are immutable in Python.
d)
SECTION B
19. Mohini has written a code to input a positive integer and display all its even (2)
factors in descending order. Her code is having errors. Rewrite the correct
code and underline the corrections made.
n=input("Enter a positive integer: ")
for i in range(n):
if i%2:
if n%i==0:
print(i,end=' ')

n=int(input("Enter a positive integer: "))


for i in range(n,1,-1):
if i%2==0:
if n%i==0: #indent
print(i,end=' ') #indent

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 2/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

20. Write two points of difference between twisted pair cable and optical fiber (2)
cable.
Twisted Pair Cable Optical Fiber Cable
It is made of metal (copper) It is made of glass
Data gets affected by Data is not affected by
electromagnetic fields. electromagnetic fields.
Attenuation is very large. Attenuation is very less.
(Any two differences)

OR
Write two points of difference between radio waves and micro waves.
Radio Waves Micro Waves
Travel in all the directions. Travel in a single direction.
Can cross solid obstacles. Cannot cross solid obstacles.
Data can be hacked easily. Data cannot be hacked easily.
(Any two differences)

21. (a) Given is a Python string declaration: (1)


myexam="Russia Ukrain"
Write the output of: print(myexam[-2:2:-2])

irUas
(1)
(b) Write the output of the code given below:
d1 = {"name": "Aman", "age": 26}
d2 = {27:'age','age':28}
d1.update(d2)
print(d1.values())

dict_values(['Aman', 28, 'age'])


22. Explain the use of ‘Foreign Key’ in a Relational Database. Give an example to (2)
support your answer.
Foreign key is used to ensure referential integrity in a Relational Database.
Example:
Let a table, named student, stores the data of all the students of a school
with the field AdmNo as the Primary Key. Let another table, named Cocurry,
in the same database stores the data of all the participants of co-curricular
activities. Let AdmNo is a foreign key in Activity and it references AdmNo of
table Student. Now, this foreign key will ensure that no invalid AdmNo is
entered in the Cocurry table, thus ensuring the referential integrity.
OR
Consider the following tables in a database:
Table Student with fields: AdmNo (Primary Key), Name, Class, Section, Phone
Table Cocurry with fields: AdmNo (Foreign key reference Student(AdmNo)),
Activity, Grade
The foreign key will ensure that no invalid AdmNo is entered in the Cocurry
table, thus ensuring the referential integrity.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 3/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

23. (a) Write the full forms of the following: (i) POP (ii) HTTPS (1)
(i) POP – Post Office Protocol
(ii) HTTPS: Hyper Text Transfer Protocol Secure
(1)
(b) Name the protocol used for remote login.
Telnet
24. Predict the output of the Python code given below: (2)
def Alpha(N1,N2):
if N1>N2:
print(N1%N2)
else: print(N2//N1,'#',end=' ')
NUM=[10,23,14,54,32]
for C in range (4,0,-1):
A=NUM[C]
B=NUM[C-1]
Alpha(A,B)

1 # 12
1 # 3

OR

Predict the output of the Python code given below:


List1 = list("Examination")
List2 =List1[1:-1]
new_list = []
for i in List2:
j=List2.index(i)
if j%2==0:
List1.remove(i)
print(List1)

['E', 'a', 'i', 'a', 'i', 'n']


25. Consider the following two commands with reference to a table, named (2)
Students, having a column named Section:
(a) Select count(Section) from Students;
(b) Select count(*) from Students;
If these two commands are producing different results,
(i) What may be the possible reason?
(ii) Which command, (a) or (b), might be giving higher value?

(i) The Section column has some NULL entries


(ii) (b) might give higher value
OR
Name the aggregate functions which work only with numeric data, and those
that work with any type of data.
sum(), avg() work only with numeric data.
max(), and count() work with any type of data.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 4/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

SECTION C
26. (a) Consider the following tables – Bank_Account and Branch:
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current

Table: Branch
ACode City
A01 Delhi
A02 Mumbai
A01 Nagpur
What will be the degree and cardinality of the Cartesian product and the
Natural join of these tables?

Degree cardinality
Cartesian Product 5 9
Natural Join 4 3

(b) Write the output of the queries (i) to (iv) based on the table TECH_COURSE (1)
given below:
Table: TECH_COURSE
CID CNAME FEES STARTDATE TID
C201 Animation and VFX 12000 2022-07-02 101
C202 CADD 15000 2021-11-15 NULL
C203 DCA 10000 2020-10-01 102
C204 DDTP 9000 2021-09-15 104
C205 Mob App Development 18000 2022-11-01 101
C206 Digital marketing 16000 2022-07-25 103
(i) SELECT TID FROM TECH_COURSE;
+------+
| TID |
+------+
| 101 |
| NULL |
| 102 | (2)
| 104 |
| 101 |
| 103 |
+------+

(ii) SELECT TID, sum(fees), MIN(FEES) FROM TECH_COURSE


GROUP BY TID HAVING COUNT(TID)=1;
+------+-----------+-----------+
| TID | sum(fees) | MIN(FEES) |
+------+-----------+-----------+
| 102 | 10000 | 10000 |
| 104 | 9000 | 9000 |
| 103 | 16000 | 16000 |
+------+-----------+-----------+

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 5/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000


and Cname like 'D%';
+-------------------+
| CNAME |
+-------------------+
| Digital Marketing |
+-------------------+

(iv) SELECT MAX(FEES) FROM TECH_COURSE WHERE FEES


BETWEEN 15000 AND 17000;
+-----------+
| MAX(FEES) |
+-----------+
| 16000 |
+-----------+

27. Write a method SHOWLINES() in Python to read lines from text file (3)
‘TESTFILE.TXT’ and display the lines which do not contain 'ke'.

Example: If the file content is as follows:


An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.

The SHOWLINES() function should display the output as:


We all pray for everyone’s safety.

def SHOWLINES():
f=open("testfile.txt")
for line in f:
if 'ke' not in line:
print(line.strip())
f.close()
OR
Write a function RainCount() in Python, which should read the content of
a text file “RAIN.TXT” and then count and display the count of occurrence of
word RAIN (case-insensitive) in the file.

Example: If the file content is as follows:


It rained yesterday
It might rain today
I wish it rains tomorrow too
I love Rain

The RainCount() function should display the output as: Rain – 2


def RainCount():
f=open('rain.txt')
data=f.read()
data=data.upper()
data=data.split()
c=data.count('RAIN')
print('Rain -',c)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 6/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations (3)
Teacher and Placement given below:
Table : Teacher
T_ID Name Age Department Date_of_join Salary Gender
1 Arunan 34 Computer Sc 2019-01-10 12000 M
2 Saman 31 History 2017-03-24 20000 F
3 Randeep 32 Mathematics 2020-12-12 30000 M
4 Samira 35 History 2018-07-01 40000 F
5 Raman 42 Mathematics 2021-09-05 25000 M
6 Shyam 50 History 2019-06-27 30000 M
7 Shiv 44 Computer Sc 2019-02-25 21000 M
8 Shalakha 33 Mathematics 2018-07-31 20000 F
Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur
(i) SELECT Department, max(salary) FROM Teacher
GROUP BY Department;
+-------------+-------------+
| Department | max(salary) |
+-------------+-------------+
| Computer Sc | 21000 |
| History | 40000 |
| Mathematics | 30000 |
+-------------+-------------+
(ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM
Teacher;
+-------------------+-------------------+
| MAX(Date_of_Join) | MIN(Date_of_Join) |
+-------------------+-------------------+
| 2021-09-05 | 2017-03-24 |
+-------------------+-------------------+
(iii) SELECT Name, Salary, T.Department, Place FROM
Teacher T, Placement P WHERE T.Department =
P.Department AND P.Department='History';
+---------+--------+------------+-----------+
| Name | Salary | Department | Place |
+---------+--------+------------+-----------+
| Saman | 20000 | History | Ahmedabad |
| Sameera | 40000 | History | Ahmedabad |
| Shyam | 30000 | History | Ahmedabad |
+---------+--------+------------+-----------+
(iv) SELECT Name, Place FROM Teacher natural join
Placement where Gender='F';
+----------+-----------+
| Name | Place |
+----------+-----------+
| Saman | Ahmedabad |
| Sameera | Ahmedabad |
| Shalakha | Jaipur |
+----------+-----------+
(b) Write the command to view all the databases in an RDBMS.
Show tables;

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 7/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

29. Write a function INDEX_LIST(S), where S is a string. The function returns (3)
a list named ‘indexList’ that stores the indices of all vowels of S.

For example: If S is "Computer", then indexList should be [1,4,6]

def INDEX_LIST(S):
indexList=[]
for i in range(len(S)):
if S[i] in 'aeiouAEIOU':
indexList.append(i)
return indexList
30. A list contains following record of a doctor: (3)
[Doc_ID, Doc_name, Phone_number, Speciality]
Write the following user defined functions to perform given operations on
the stack named "status":
(i) Push_element() - To Push an object containing Doc_ID and Doc_name
of doctors who specialize in Anesthesia to the stack.

(ii) Pop_element() - To Pop the objects from the stack and display them.
Also, display “Stack Empty” when there are no elements in the stack.
For example: If the lists of Doctors' details are:
['D01', "Gurdas", “99999999999”,"Anesthesia”]
["D02", "Julee", “8888888888”,"cardiology"]
[D03",“Murugan”,”77777777777”,”Anesthesia”]
["D04",“Ashmit”, “1010101010”,”Medicine”]
The stack should contain
['D03', 'Murugan']
['D01', 'Gurdas']
The output should be:
['D03', 'Murugan']
['D01', 'Gurdas']
Stack Empty

def Push_element(D):
if D[-1]=="Anesthesia":
status.append([D[0],D[1]])
def Pop_element():
while status:
print(status.pop())
print("Stack Empty")
OR
Write a function in Python, Push(KItem), where KItem is a dictionary
containing the details of Kitchen items– {Item:price}.
The function should push the names of those items in a stack which have price
less than 100. Also display the average price of elements pushed into the
stack.
For example: If the dictionary contains the following data:
{"Spoons":116,"Knife":50,"Plates":180,"Glass":60}
The stack should contain
Glass
Knife
The output should be:
The average price of an item is 55.0

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 8/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

def Push(KItem):
st=[] #stack
c,s=0,0
for k,v in KItem.items():
if v<100:
st.append(k)
c+=1
s+=v
if c!=0:
av=s/c
print("The average price of an item is",av)
SECTION D
31. Total-IT Corporation, a Karnataka based IT training company, is planning to set up training
centers in various cities in next 2 years. Their first campus is coming up in Kodagu district.
At Kodagu campus, they are planning to have 3 different blocks, one for AI, IoT and
DS (Data Sciences) each. Each block has number of computers, which are required to
be connected in a network for communication, data and resource sharing. As a network
consultant of this company, you have to suggest the best network related solutions for them
for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between
various blocks/locations and other given parameters.

Distance between various blocks/locations:


Block Distance
IT to DS 28 m
IT to IoT 55 m
DS to IoT 32 m
Kodagu Campus to Coimbatore Campus 304 km

Number of computers:
Block Number of Computers
IT 75
DS 50
IoT 80

(i) Suggest the most appropriate block/location to house the SERVER in


the Kodagu campus (out of the 3 blocks) to get the best and effective
connectivity. Justify your answer.
IoT block, as it has the maximum number of computers.
(ii) Suggest a device/software to be installed in the Kodagu Campus to
take care of data security.
Firewall
(iii) Suggest the best wired medium and draw the cable layout (Block to
Block) to most efficiently connect various blocks within the Kodagu
Campus. (1)
Optical fiber

(1)

(1)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 9/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

(1)

(1)

(iv) Suggest the placement of the following devices with appropriate


reasons: a) Switch/Hub b) Router
a) Switch/Hub: In each block to interconnect the computers in that
block.
b) Router: In IoT block (with the server) to interconnect all the
three blocks.
(v) Suggest a protocol that shall be needed to provide Video Conferencing
solution between Kodagu Campus and Coimbatore Campus.
VoIP
32. (a) Write the output of the code given below: (2)
p=8
def sum(q,r=5):
global p
p=(r+q)**2
print(p, end= '#')
a=2; b=5; sum(b,a)
sum(r=3,q=2)

49#25# (3)

(b) The code given below accepts the roll number of a student and increases
the marks of that student by 5 in the table Student. The structure of a
record of table Student is:
RollNo – integer; Name – string; Clas – integer; Marks – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is abc
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:

import mysql.connector as mysql def sql_data():


con1=mysql.connect(host="localhost",user="root",
password="abc")
mycursor= con1.cursor()
mycursor.execute("use school;") #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
querry="update student set marks=marks+5 where
RollNo={}".format(rno)
mycursor.execute(querry) #Statement 2
con1.commit() # Statement 3
print("Data updated successfully")

Statement 1 – to open/activate the school database.

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 10/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

Statement 2 – to execute the command that updates the record in the table
Student.
Statement 3- to make the updation in the database permanent
OR
(a) Predict the output of the code given below:
s="3 & Four"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'A' and s[i] <= 'Z'):
m = m +s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
m = m +s[i-1]
if (s[i].isdigit()):
m = m + s[i].lower()
else: m = m +'-'
print(m)
3---F-F-o-u-
(b) The code given below reads records from the table named student and
displays only those records who have marks greater than 75. The structure
of a record of table Student is:
RollNo – integer; Name – string; Clas – integer; Marks – integer

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is abc
• The table exists in a MYSQL database named school.
• The details (RollNo, Name, Clas and Marks) are to be accepted from
the user.
Write the following missing statements to complete the code:
Statement 1 – to create the cursor object
Statement 2 – to execute the query that extracts records of those
students whose marks are greater than 75.
Statement 3 - to read the complete result of the query (records whose
marks are greater than 75) into the object named data,
from the table student in the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="school")
mycursor= con1.cursor() #Statement 1
print("Students with marks greater than 75 are : ")
mycursor.execute("select * from student where
marks>75" #Statement 2
data= mycursor.fetchall() #Statement 3
for i in data:
print(i)

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 11/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

33. (a) What is the advantage of using a csv file for permanent storage? (5)
A csv file can be managed using any text editor, spreadsheet program, or
a program.
(b) Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD() – To accept and add data of an item to a CSV file ‘furniture.csv’.
Each record consists of Fur_id, Description, Price, and Discount.

import csv
def ADD():
with open('furniture.csv','a',newline='') as f:
fid=input("Enter furniture ID: ")
desc=input("Enter Description: ")
pr=input("Enter Price: ")
disc=input("Enter discount: ")
rec=[fid,desc,pr,disc]
w=csv.writer(f)
w.writerow(rec)
(ii) COUNTR() – To count the number of records present in ‘furniture.csv’
whose price is less than 5000.
import csv
def COUNTR():
with open('furniture.csv') as f:
r=csv.reader(f)
c=0
for rec in r:
if eval(rec[2])<5000:
c+=1
print("Number of such records =",c)
OR
(a) Give any one point of difference between a binary file and a csv file.
A binary file can be managed only by some specific applications/program
whereas a csv file can be managed using multiple general purpose
applications/programs.
(b) Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD() – To accept and add data of an item to a binary file
‘furniture.dat’. Each record of the file is a list [Fur_id,
Description, Price, and Discount]. Fur_Id and Description are
of str type, Price is of int type, and Discount is of float type.
def ADD():
with open('furniture.dat','ab') as f:
fid=input("Enter furniture ID: ")
desc=input("Enter Description: ")
pr=eval(input("Enter Price: "))
disc=eval(input("Enter discount: "))
rec=[fid,desc,pr,disc]
pickle.dump(rec,f)
(ii) COUNTR() – To count the number of records present in ‘furniture.dat’
whose price is less than 5000.
def COUNTR():
with open('furniture.dat','rb') as f:
c=0
try:

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 12/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

while True:
rec=pickle.load(f)
if rec[2]<5000:
c+=1
except:
pass
print("Number of such records =",c)
SECTION E
34. Tushar is a Python programmer. He has written a code and created a binary (4)
file record.dat with employeeid, ename and salary. The file contains 10
records.

He now has to delete a record based on the employee id entered by the user.
For this purpose, he creates a temporary file, named temp.dat, to store all
the records other than the record to be deleted. If the employee id is not
found, an appropriate message should to be displayed.

As a Python expert, help him to complete the following code (by completing
statements 1, 2, 3, and 4) based on the requirement given above:

(i) Complete Statement#1 to import the required module.


(ii) Write the correct statement required to open a temporary file
named temp.dat. (#Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data
from the binary file, record.dat
(iv) What should be written in Statement 4 to write the required records
in the file temp.dat?

Import pickle #Statement 1


def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("temp.dat","wb") #Statement 2
found=False
eid=int(input("Enter employee id: "))
while True:
try:
rec= pickle.load(fin) #Statement 3
if rec["Employee id"]==eid:
found=True
else:
pickle.dump(rec,fout) #Statement 4
except:
break
if found==True:
print("Record deleted.")
else:
print("Employee with such id is not found")
fin.close()
fout.close()

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 13/14


AnsKey/SQP1/CS (083)/XII/2022-23/YK/Full Syllabus

35. Navdeep creates a table RESULT with a set of records to maintain the marks (4)
secured by students in Sem1, Sem2, Sem3 and their division. After creation of
the table, he has entered data of 7 students in the table.
ROLL_NO SNAME SEM1 SEM2 SEM3 DIVISION
101 KARAN 366 410 402 I
102 NAMAN 300 350 325 I
103 ISHA 400 410 415 I
104 RENU 350 357 415 I
105 ARPIT 100 75 178 IV
106 SABINA 100 205 217 II
107 NEELAM 470 450 471 I

Based on the data given above answer the following questions:

(i) Can Name be a candidate key of the table? Justify your answer.
Yes. Based on the given data we observe that each entry in SNAME
column is unique. Therefore, SNAME can be the a Candidate key.

(ii) If a column is added and 3 rows are deleted from the table result, what
will be the new degree and cardinality of the above table?
Degree: 7, Cardinality: 4

(iii) Write the statements to:


a) Insert the following record into the table
Roll_No- 108, Name- Aadit, Sem1- 470, Sem2-444, Sem3-475, Div– I.
insert into RESULT values(108,'Aadit',470,444,475,'I' );
b) Increase the SEM2 marks of the students by 3% whose Name ends with
'A'.
update result set sem2=sem2*1.03 where sname like '%A';
OR (Option for part iii only)
(iii) Write the statements to:
a) Delete the record of students securing IV division.
delete from result where division='IV';
b) Add a column GRADE, of type char of length 3 characters to the
RESULT table.
Alter table RESULT add column GRADE char(3);

Ph:65891262 / web: www.yogeshsir.com / YouTube: www.youtube.com/Learnwithyk Page 14/14

You might also like