Class 12 Cs All KV Region Papers 2022-23 Removed
Class 12 Cs All KV Region Papers 2022-23 Removed
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.”
Q20. Write two points of difference between Bus topology and star topology. (2)
OR
Write two points of difference between XML and HTML.
Q22. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give example to (2)
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
Q25. Differentiate between order by and group by clause in SQL with appropriate example. (2)
OR
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:
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
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.
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:
Orbit
Building
Sunrise
Jupiter
Building
Building
Oracle
Building
#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
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
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:
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.
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
b) Write output of the queries (i) to (iv) based on the table Sportsclub
Table Name: Sportsclub
playerid pname sports country rating salary
5|Page
10007 PAUL SNOOKER USA B 10000
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
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)
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
_________________ #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)
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])
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
OR
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
b) Write output of the queries (i) to (iv) based on the table Sportsclub
Table Name: Sportsclub
playerid pname sports country rating salary
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.
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';
L = [12,10,15,20,25]
modilst(L)
print(L)
OR
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)
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))
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
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.
OR (only in a part)
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)
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()
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
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)
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} )
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
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
(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:
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”)
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
(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) 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.
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.
3
What will be the output of
print(Ist1.index(23)) 2
break
print(st)
print(count)
OR
below:
Predict the output of the Python code given
gama = 0
for i in range(1,6,2):
alpha+i
beta +myvaluefi-1]+ "#"
gama + myvalue[i]
SELECT, ALTER
SECTIONC
26. T(a)Consider the following
tables- Applicants and Centre 1+2
Table: Applicants
Appno Name Subject
C01 Mohan English
Table: Centre
Appno City
C02 Madurai
C03 Chennai
C02 Jaipur
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
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
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
return(answer)
print(number1, 'times', number2, '", answer)
output multiply(5, 5)
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:
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:
OR
(i) ShowRec0 -
(o 2es
and April months in MOTOR table as shown below +2
(b) Display the names of motor bikes which are sold more than 200 in
January month.
OR (Optionfor part ii only)
#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 : "
try:
while True:
rec pickle._ #statement4
i fAuthor=rec[2]:
num=num+1
except:
fobj.close0
return num
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
(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+
(a) Statement 1
(b) Statement 2
(c) Statement 3
(d) Statement 4
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) 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’)
(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
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).
Table: Applicants
Appno Name Subject
C01 Mohan English
C02 Raju Hindi
Table : Centre
Appno City
C02 Madurai
C03 Chennai
C02 Jaipur
(b) Write the output of the queries (i) to (iv) based on the table, Car
given below:
(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'.
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.
Ans:
def rdlines():
file = open('visitors.txt','r')
for line in file:
if line[0] == 'P':
print(line)
file.close()
For example:
If the list Num is:
[66, 75, 40, 32, 10, 54]
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())
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
Ans:
(i) Block B
Justification- Block B has maximum number of computers. Reduce
traffic.
(ii)
A B C
D E
(b) The code given below inserts the following record in the table
Student:
Rollno – integer
Name – string
Age – integer
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
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()
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:
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()
The csv.writer object adds delimitation to the user data prior to storing
data in the csv file on storage disk. –1 mark
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:
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()))
Table: Item
SCode IPRICE ICity
S01 1200 Delhi
S02 2500 Mumbai
S01 3200 Maharashtra
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.
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”]
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.
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:
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.
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:
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
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:
######################
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.
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
For example:
If L contains [9,4,0,3,11,56]
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
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()
(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)
************************
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
a) 2 + 3 == 4 +5 ==7 b) 0 ==1 == 2
a) 2**3**2 b) (2**3)**2
num1 = num1 *3
print(num1)
6. Which of the following is used toread n characters from afile object“ f1” . 1
print(S) #Statement2
(a) Primary Key (b) Foreign Key (c) CandidateKey (d) AlternateKey
11. Which of the following statements correctly explain the function of seek() method? 1
12. What is break statement in the context of flowof control in the python programming. 1
>>>L1=[8,11,20]
>>>L1*3
(b) BothA and Raretrue and Ris not thecorrect explanation for A
SECTIONB
30=n
fori in range(0,n)
IF i%4==0:
print (i*4)
Else:
print (i+4)
OR
D1['age'] =27
D1['address'] = "Delhi"
print(D1.items())
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=” #“ )
OR
def my_func(var1=100,var2=200):
var1+=10
return var1+var2
print(my_func(50),my_func())
OR
(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
CITYNAME CHAR(30)
SIZE INTEGER(3)
AVGTEMP INTEGER
POLLUTIONRATE INTEGER
POPULATION INTEGER
Couldn'tputHumpty togetheragain
OR
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.
OR
SECTIOND
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.
(iv) Thecompany is planning to link itshead office situated in New Delhi with the
offices in hilly areas. Suggest a way to connect iteconomically.
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="#")
OR
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)
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.
OR
Writea Program inPython thatdefines and calls the following user defined functions:
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
Table: Posting
1 History Agra
2 Mathematics Raipur
3 ComputerScience Delhi
c)To add foreign key to newly created column P_ID in TeacherTable assuming that
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
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:
else:
fin.close()
fout.close()
(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
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
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
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
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.
It rained yesterday.
It might rain today.
I wish it rains tomorrow too.
I love Rain.
.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:
(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:
(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
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:
(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
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
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;
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
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?
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}
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?
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
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
(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+
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
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:
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;
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
(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:
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
(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
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
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
(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
Degree- 4
Cardinality- 3
(Any other suitable example)
(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()
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)
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.
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
(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
mycursor._________________ # Statement 3
mydb.commit()
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
import____________#Statement-1
sqlist=list()
fout=open(“mydata.dat”,____________) #Statement-2
_____________(sqlist,fout) #Statement-3
fout.close()
fin=open(“Mydata.dat”, “rb” )
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:
No of Computers
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.
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
_________________________________________________________________________________________
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( )
b. False
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
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
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.
c. PPP
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
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.
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.
Ans : lyli#
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=' ')
OR
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
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
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 :
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?
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
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)
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
(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’}
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
Finance Resource
ii. Admin
iii. SWITCH/HUB
iv. ADMIN & FINANCE
v. (c) Optical Fiber
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.
OR
(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.
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
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:
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
3 If Statement in Python is __ 1
(a) looping statement (b) selection statement (c) iterative (d) sequential
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]
if not False:
print(10)
else:
print(20)
Page 1 of 9
(a) 10 (b) 20 (c) True (d) False
(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
10 Identify the device on the network which is responsible for forwarding data from one device to 1
another
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?
14 Which of the following clause is used to remove the duplicating rows from a select statement? 1
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;‐
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:
21 What do you mean by Foreign key? How it is related with Referential Integrity? 2
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?
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
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.
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.
FINANCE BLOCK
(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?
The Following program code is used to increase the salary of Trainer SUNAINA by 2000.
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)
The Following program code is used to view the details of the graduate whose subject is
PHYSICS.
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()
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) <>
(a) state [-5:] (b) state [4:] (c) state [:4] (d) state [:-4]
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
Ans: d) d=f.readlines()
10 Identify the device on the network which is responsible for forwarding data from one device to 1
another
16 Which of the following method is used to create a connection between the MySQL database and 1
Python?
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;‐
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:
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
OR
Page 4 of 13
What do you mean by Guided Media? Name any three guided media?
Ans –
Guided media – Physical Connection – ½ mark
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)
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)
Ans:
(a) (b) (c)
Itemane MONTHNAME(Dateofstock) Price*DIscount
White lotus February 625000
Comfort Zone December 340000
Wood Comfort February 112500
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.
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.
FINANCE BLOCK
(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
The Following program code is used to increase the salary of Trainer SUNAINA by 2000.
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)
The Following program code is used to view the details of the graduate whose subject is
PHYSICS.
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:
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()
Ans:
(i) r
(ii) read()
(iii) line.split()
(iv) len(c)<4
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)
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])
OR
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
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'.
Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur
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.
(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.
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.
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.
Number of computers:
Block Number of Computers
IT 75
DS 50
IoT 80
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
(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
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:
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
(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.
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)
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)
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())
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
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 |
+------+
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'.
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.
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;
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.
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
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.
Number of computers:
Block Number of Computers
IT 75
DS 50
IoT 80
(1)
(1)
(1)
(1)
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
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
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:
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:
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
(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