50% found this document useful (2 votes)
5K views175 pages

XII - Comp. Scioence

Uploaded by

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

XII - Comp. Scioence

Uploaded by

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

NAVODAYA VIDYALAYA SAMITI

SHILLONG REGION

SADHANA PROGRAM
(2024-25)

PRACTICE PAPERS
For
CLASS XII

SUBJECT: COMPUTER SCIENCE


SUBJECT CODE: (083)
2|Page
Development Committee

NAME DESIGNATION & JNV OF THE


S. No. ROLE
RESOURCE PERSON

SH. ABDUL GANI, PRINCIPAL


1 PM SHRI JNV SOUTH WEST GARO HILLS, COORDINATOR
MEGHALAYA
MS. NISHA NAIR, PGT COMPUTER SCI.
2 JNV SOUTH SIKKIM, ASSAM MEMBER

3 SH. DAYANANDA NATH, PGT COMP. SCI. MEMBER


JNV DARRANG, ASSAM

4 SH. SANJAY PANDEY, PGT COMPUTER SCI. MEMBER


JNV KAMRUP, ASSAM

5 SH. S.K. GOND, PGT COMPUTER SCI. MEMBER


JNV SONITPUR, ASSAM

6 SH. D.S.BORO, PGT COMPUTER SCI. MEMBER


JNV KOKRAJHAR. ASSAM

3|Page
CONTENTS:-
S.NO. PARTICULERS PAGE NO.

1 Practice Paper Set No. 1 5-19

2 Answer Key Set No. I 20-31

3 Unit-I Python Revission Tour 32-47

4 Practice Paper Set No. 2 48-56

5 Answer Key Set No. 2 57-62

6 Unit-II, Functions, File Handling 63-114


& Data Structure
7 Practice Paper Set No. 3 115-122

8 Answer Key Set No. 3 123-126

9 Unit-III,Database Management 127-138

10 Practice Paper Set No. 4 139-148

11 Answer Key Set No. 4 149-155

12 Unit-IV, Computer Networks 156-159

13 Practice Paper Set No. 5 160-168

14 Answer Key Set No. 5 169-175

4|Page
PRACTICE QUESTION PAPER (THEORY)
CLASS: XII SESSION: 2024-25 COMPUTER
SCIENCE (083)

Time allowed: 3 Hours Maximum Marks: 70

General Instructions:
● This question paper contains 37 questions.
● All questions are compulsory. However, internal choices have been provided in some questions.
Attempt only one of the choices in such questions
● The paper is divided into 5 Sections- A, B, C, D and E.
● Section A consists of 21 questions (1 to 21). Each question carries 1 Mark.
● Section B consists of 7 questions (22 to 28). Each question carries 2 Marks.
● Section C consists of 3 questions (29 to 31). Each question carries 3 Marks.
● Section D consists of 4 questions (32 to 35). Each question carries 4 Marks.
● Section E consists of 2 questions (36 to 37). Each question carries 5 Marks.
● All programming questions are to be answered using Python Language only.
● In case of MCQ, text of the correct answer should also be written.

Q No. Section-A (21 x 1 = 21 Marks) Marks


What will be the value of X in the following Python expression?
1. (1)
X = 2+9*((3*12)-8)/10
a) 30.0
b) 30.8
c) 28.4
d) 27.2
What will be the output of the following code?
2. num = [1, 2, 3, 4, 5]
for i in range(len(num)):
num[i] *= 2
print(num)
(1)
a) [1, 2, 3, 4, 5]
b) [2, 4, 6, 8, 10]
c) [1, 4, 9, 16, 25]
d) [2, 3, 4, 5, 6]
Find the invalid identifier from the following:
3.
a) None
b) Name_12 (1)
c) _123num
d) true

5|Page
In Python, ………….. defines a block of statements.
4.
a) Block
b) loop
c) indentation (1)
d) { }

5. What will be the output of the following code snippet?


message= "Hai Python" (1)
print(message[-2::-2])
A) iyhn
B) oiyH
C) otPiH
D) oyi

Assume the tuple superstore is (10,20,30,40,50), which of the following is correct


6.
syntax for slicing operation?
A) print(superstore[0:])
B) print(superstore[:2])
C) print(superstore[:-2]) (1)
D) All of these

What is the output of the following code?


7. my_dict = {"apple": 3, "banana": 2, "cherry": 5}
keys = my_dict.keys()
print(keys)
A) ["apple", "banana", "cherry"] (1)
B) ["apple"]
C) ["banana"]
D) dict_keys(["apple", "banana", "cherry"])
Given str1=”Hello” and str2=”Bye”, what is the output produced by the following
8.
expressions:
(a) “Let us all say” + str1
(1)
(b) 3 * str1 + 4 * str2

Consider a table with the following structure:


9.
Employee(Emp_id,Emp_name,Dept,Desig,Basic)
In this table which attribute can be used as a primary key?
A) Emp_id (1)
B) Emp_name
C) Dept
D) Desig

6|Page
10. State whether the following statement is True or False:
In a try-except block, if an exception occurs but it is not handled by any except
clause, then the exception is ignored and the program continues to execute.
(1)
Suppose the content of a text file Notes.txt is:
11.
“ The way to get started is to quit talking and being doing”
(1)
Complete the following Python code with appropriate functions to get the output
as:
“quit talking and being doing”
F=open(“Notes.txt”)
F. _______
S= F. _______
Print(S)

What will be the output of the following code?


12. def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero")
finally:
print("Finally block")
divide(10, 0) (1)
A) Error: Division by zero
Finally block
B) Finally block
C) The code will raise an exception and terminate.
D) None of the above.

13. Sonal needs to display name of teachers, who have “O” as the third character in (1)
their name. She wrote the following query:
SELECT NAME FROM TEACHER WHERE NAME = ”**O”;
But the query isn’t producing the result. Identify the problem and write the correct
query.

Which of the following is a DDL command?


14.
A) SELECT
B) ALTER
C) INSERT (1)
D) UPDATE

7|Page
Consider the following statement:
15.
SELECT * FROM product ORDER BY rate _______, item_name _______ ;
Which of the following option should be used do display the ‘rate’ from greater to
smaller and ‘name’ in alphabetical order? (1)
A) ASC, DESC
B) DESC, ASC
C) Descending, Ascending
D) Ascending, Descending

To make the changes made by any SQL Queries permanently in database, which
16. function is used after execution of the query ?
A) save()
B) commit() (1)
C) execute()
D) dump()
Given below are two addresses.
17.
(i) https://navodaya.gov.in/nvs/en/Home1
(ii) 182.68.34.170
Identify which one of the above is an IP address and which one is a URL?
(1)
Expand the following terms:
18.
(i) SMTP
(ii) VoIP
(1)
Which one is False about MAC address?
19. A) It is Physical Address of any device connected to the internet.
B) We can change MAC address of a device. (1)
C) It is the address of NIC card install in network device.
D) It is used for track the user’s over internet.

Q20 and Q21 are Assertion (A) and Reason(R) 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

20. Assertion (A): Key word arguments are related to the function calls.
Reasoning (R): When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name. (1)

8|Page
21. Assertion (A): The HAVING clause is used with aggregate functions.
Reasoning (R): WHERE clause places condition on individual rows.
(1)

Q No Section-B ( 7 x 2=14 Marks) Marks


Write the output of the following code snippet:
22.
tup=(‘India’,)
(2)
N=5
for i in range(int(N)):
tup=(tup,)
print(tup)

23. What will be the output of the following code snippet?


(2)
a,b,c=10,200,90
str1="Hello"
str2="JNV"
str3="Python"
print(a<b and a<c)
print(b>c or a>=c and a<c)
print(a<b>c)
print(str1>str2 and str2<str3)

What will be the output generated by the following Python code:


24.
def fun1(m=8,n=10):
global x
x=4 (2)
y=6
print (m+n-x)
def fun2():
x=5
return x
print(fun2())
a,b=50,10
x=200
fun1(b)
fun1()
print(x)

9|Page
What possible output(s) are expected to be displayed on the screen at the time of
25. execution of the program from the following code? Also, specify the maximum and
minimum values that can be assigned to the variable number.
import random
string="CBSEONLINE"
number=random.randint(0,3)
n=len(string)-1
while string[n]!="L": (2)
print(string[n]+string[number]+"#",end="")
number+=1
n-=1
A) ES#NE#IO#
B) LE#NO#ON#
C) NS#IE#LO#
D) EC#NB#IS#

Find the errors in the following Python code and rewrite the code after
26.
correcting errors and underline the corrected code.
Def HowMany(ID,Val):
count=0
for I in ID
If i=val: (2)
count=count + 1
print(count)
L=[11,12,23,34,45,56,65]
Va=22
HowMany()
OR

Find the errors in the following Python code and rewrite the code after
correcting errors and underline the corrected code.
Def string#reverse(str1):
rstr1=””
index=str1.len()
while index>0;
rstr1+=str1(index-1)
index=index-1
return rstr1
print(string_reverse(‘123abcd’))

10 | P a g e
27. Observe the table CLUB given below:
Table : CLUB
Member_ID Name Address Age Fee
M0001 Ashik Shillong 20 3500
M0002 Sumit Kolkata 21 2500 (2)
M0003 Neethu Kochi 19 3500
M0004 Nithya New Delhi 20 4000
(i) What is the cardinality and degree of the given table?
(ii) Which field should be made the primary key? Justify your answer.

28. Identfy the type of topology on the basis of the following:


(i) Since every node is directly connected to the server, a large amount of cable is (2)
needed which increases the installation cost of the network.
(ii) It has a single common data path connecting all the nodes.

OR
Name the protocol:
(i) Used to transfer voice using packet switching network.
(ii) Used for chatting between two groups or between two individuals.

Q No. Section-C ( 3 x 3 = 9 Marks) Marks

29. A text file “Book.txt” contains a paragraph. Write a Python function that searches
for a given character and reports the number of occurrence of the character in the
file. (3)

OR

Consider a file “Story.txt” whose content is as shown below:


Ravi has gone to his friend’s house.
His friend’s name is Rakhi.
Her house is far from his house.
Write a Python function CountHisHer() which reads the contents of the text file
“Story.txt” and counts the words His and Her (not case sensitive).

11 | P a g e
30. Consider a stack named ItemStack that contains records of items in a shop. Each
item record is represented as a list containing item_no, item_name, and
item_price.
Write the following user-defined functions in Python to perform the specified
operations on the stack ItemStack:
(I) push_item(ItemStack, new_item): This function takes the stack ItemStack
and a new item record new_item as arguments and pushes the new item
record onto the stack.
(II) pop_item(ItemStack): This function pops the topmost item record from the
stack and returns it. If the stack is already empty, the function should
display "Underflow".
(III) peep(ItemStack): This function displays the topmost element of the stack (3)
without deleting it. If the stack is empty, the function should display
'None'.
OR
Write a user-defined function `div_5(N)` which accepts a list of integers in a
parameter `N` and pushes all those integers which are divisible by 5 from the list `N`
into a Stack named `FactNumbers`.
Write function pop_div5() to pop the topmost number from the stack and returns it.
If the stack is already empty, the function should display "Empty".
Write function Disp_div5() to display all element of the stack without deleting them.
If the stack is empty, the function should display 'None'.

For example:
If the integers input into the list `VALUES` are: [10, 5, 18, 35, 112]

Then the stack `FactNumbers` should store: [10, 5, 35]


Predict the output of the code given below:
31.
s="Welcome2cs@JNV"
n=len(s)
m=""
for i in range(0,n):
if(s[i]>='a' and s[i]<='m'):
m+=s[i].upper()
(3)
elif(s[i]>='n' and s[i]<='z'):
m+=s[i-1]
elif(s[i].isupper()):
m+=s[i].lower()
else:
m+='&'
print("The string is: ",m)

12 | P a g e
print("The new string is: ",m[::-2])

OR

Predict the output of the code given below for the following inputs:
(i) NVS@24 (ii) jnv_N1
mystr = input("Enter a string:\n")
newstr = ""
count=0
for i in mystr:
if count % 2 != 0:
newstr = newstr + str(count)
else:
if i.lower():
newstr = newstr + i.upper()
else:
newstr = newstr + i
count += 1
print(newstr)

Q No. Section-D ( 4 x 4 = 16 Marks) Marks

13 | P a g e
Consider the following tables EMPLOYEE and DEPARTMENT:
32.
TABLE: EMPLOYEE

TCode TName DepCode Salary Age JoinDate


15 Sameer Sharma 123 75000 39 01-Apr-2007
21 Ragvinder K 101 86000 29 11-Nov-2005
3 Rama Gupta 119 52500 43 03-Mar-2010
46 CR Menon 103 67000 38 12-Jul-2004 (4)
77 Mohan Kumar 103 63000 55 25-Nov-2000
81 Rajesh Kumar 19 74500 48 11-Dec-2008
8 Sanjeev P 101 92600 54 12-Jan-2009
93 Pragya Jain 123 32000 29 05-Aug-2006

TABLE: DEPARTMENT

DepCode DepName DepHead


101 ACCOUNTS Rajiv Kumar
103 HR P K Singh
119 IT Yogesh Kumar
123 RESEARCH Ajay Dutta

Write SQL commands for the following statements:


i) To display all DepName along with the DepCode in descending order of
DepCode.
ii) To display the average age of Employees in DepCode as 103.
iii) To display the name of DepHead of the Employee named “Sanjeev P”
iv) To display the details of all employees who has joined before 2007 from
EMPLOYEE table.

OR

2. Give the output of the following SQL queries:


i) SELECT COUNT (DISTINCT DepCode) FROM EMPLOYEE;
ii) SELECT MAX(JoinDate), MIN (JointDate) FROM EMPLOYEE;
iii) SELECT TName, DepHead FROM EMPLOYEE E, DEPARTMENT D WHERE
E.DepCode = D.DepCode;

14 | P a g e
iv) SELECT COUNT (*) FROM EMPLOYEE WHERE Salary > 60000 AND Age >
30;

Write a function in Python to search and display details, whose destination is


33. “Cochin” from binary file “Bus.dat”. Assuming the binary file is containing the
following elements in the list:
1. Bus Number
2. Bus Starting Point
3. Bus Destination

OR
(4)
Consider a binary file “Salary.dat” that has structure[Employee id, Employee name,
Salary]. Write a function countrec() in Python that would read contents of the file
“Salary.dat” and display the details of those employees whose salary is above 20000
and less than 50000.

Write the SQL command for the following on the basis of given table.
34.
Table : SPORTS
StudentNo Class Name Game1 Grade1 Game2 Grade2
10 7 Sammer Cricket B Swimmi A
ng
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A (4)
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Athletic C
s

(A)
i)Display the names of the students who have grade “A‟ in either Game 1 or
Game 2 or both.
ii)Display the number of students having the GRADE1 as “A‟ in Game1.
iii)Display the names of students who have same game for both Game1 and
Game2.
iv)Display the games taken by the students whose name starts with “A‟
15 | P a g e
OR
(B) Give the output of the following sql statements as per table given above.
i) SELECT COUNT(*) FROM SPORTS.
ii) SELECT DISTINCT Class FROM SPORTS.
iii) SELECT MAX(Class) FROM STUDENT;
vi) SELECT COUNT(*) FROM SPORTS GROUP BY Game1;

The given program is used to connect python with MySQL and show all the
35.
data present in the table “stmaster” from the database “oraclenk”. You are
required to complete the statements so that the code can be executed
properly.
import _____.connector __ pymysql #STATEMENT1
dbcon=pymysql._____________(host=”localhost”,user=”roo
t”,________=”sia@1928”) #STATEMENT2
if dbcon.isconnected()==False
print(“Error in establishing connection:”) (4)
cur=dbcon.______________() #STATEMENT3
query=”select * from stmaster”
cur.execute(_________)#STATEMENT4
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.close()

Q.No. SECTION E (2 X 5 = 10 Marks) Marks


TQ CONSULTANTS is a professional consultancy company. The company is
36.
planning to set up new offices in India with its hub at Gurugram. As a network
adviser, you have to understand their requirements and suggest to them the best
available solutions.

(5)

16 | P a g e
Block-to-Block distance (in Mtrs.):

Block(From) Block (To) Distance


Human Resources Conference 60
Human Resources Finance 60
Conference Finance 120

Expected Number of Computers to be installed in each block:


Block Computers
Human Resorces 125
Confrence 25
Finance 60

i. What will be the most appropriate block where organization 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 to connect the
new set-up of offices in Nagpur with its London base office?
(i) Co-axial cable (ii) Satellite Link (iii) Ethernet Cable
iv.Which of the following devices will you suggest to connect each computerin each
of the above buildings?
(i)Gateway (ii) Switch (iii) Modem

17 | P a g e
v.Write names of any two popular OpenSource Software which are used as
Operating Systems.

37. Consider the following csv file and the code fragment associated with the following
csv file :

import csv
f=open("c:\\stud.csv")
fobj=csv.reader(f)
for k in fobj:
for j in k:
print(j, end=’’)
break
_____ # Line 1

I.What will be the output printed by the above code?


a. SLNO12345
b. SLNO
c. The entire content
d. Error

II.What will be the output printed by the above code if the break is replaced with
continue?
a. SLNO12345
b. SLNO
c. The entire content
d. Error

III.What will occur if the file stud.csv is not existing in the mentioned path?
a. It will create a new one
b. It will create an error
c. None of the above
d. It will cause a system reboot

IV.Which statement in the above code will help to move to the next record?
a. fobj.next()
b. next(fobj)
c. fobj.move()

18 | P a g e
d. fobj.forward()

V. What must be written in Line 5?


a. F.close()
b. f.close()
c. fobj.close()
d. csvfile.close()

19 | P a g e
MARKING SCHEME
Class: XII Session: 2024-25
Computer Science (083)

Time allowed: 3 Hours Maximum Marks: 70


Q No. SECTION A (21X1=21) Marks
1. (D) 27.2 (1)
(1 mark for correct answer)
2. (B) [2,4,6,8,10]
(1)
(1 mark for correct answer)
3. (A) None
(1)
(1 mark for correct answer)
4. (C) indentation
(1)
(1 mark for correct answer)
5. otPiH
(1)
(1 mark for correct answer)
6. (D) All of these
(1)
(1 mark for correct answer)
7. (D) dict_keys(["apple", "banana", "cherry"])
(1)
(1 mark for correct answer)
8. (a) Let us all say Hello
(b) HelloHelloHelloByeByeByeBye (1)

(1/2 marks for each correct answer)


9. (A) Emp_id
(1)
(1 mark for correct answer)
10. False
(1)
(1 mark for correct answer)
11. (a) seek(29)
(b) read() (1)

(1/2 marks for each correct answer)


12. (A) Error: Division by zero
Finally block (1)
(1 mark for correct answer)
13. SELECT name FROM teacher WHERE name LIKE “_ _O%”; (1)
(1 mark for correct answer)

20 | P a g e
14. (B) ALTER
(1)
(1 mark for correct answer)
15. (B) DESC, ASC
(1)
(1 mark for correct answer)
16. (B) COMMIT
(1)
(1 mark for correct answer)
17. (i) URL
(ii) IP Address (1)

(1/2 mark for each correct answer)


18. (i) Simple Mail Transfer Protocol
(ii) Voice over Internet Protocol (1)

(1/2 mark for each correct answer)


19. (B) We can change MAC address of a device
(1)
(1 mark for correct answer)
20. (A) Both A and R are True and R is the correct explanation for A
(1)
(1 mark for correct answer)
21. (B) Both A and R are True and R is not the correct explanation for A
(1)
(1 mark for correct answer)

Q No. SECTION B (7 X 2 =14) Marks


22. (('India',),)
((('India',),),)
(((('India',),),),)
(2)
((((('India',),),),),)
(((((('India',),),),),),)
(2 marks for correct answer)
23.
True
(2)
True

True

False

(½ x 4 = 2 Marks for each correct output)

21 | P a g e
24. 5
16
14
4 (2)

(1/2 mark for each correct output)

25. Options (A) and (D) are possible.


Number:- Minimum Value=0 and Maximum Value=3
(2)

(1 mark for each correct answer)

26. def HowMany(ID,Val):


count=0
for I in ID:
If i= =val:
count=count + 1
(2)
print(count)
L=[11,12,23,34,45,56,65]
Va=22
HowMany(L, Va)

OR
def string_reverse(str1):
rstr1=””
index=len(str1)
while index>0;
rstr1+=str1[index-1]
index=index-1
return rstr1
print(string_reverse(‘123abcd’))

(½ mark each for correcting 4 mistakes)

22 | P a g e
27.
(i) Cardinality: 4
Degree: 5

(ii) Member_ID should be made the primary key as it uniquely identifies


each record of the table.
(2)
(1/2 marks for correct cardinality and degree)
(1/2 marks for correct field and justification)

28.
(i) Star Topology

(ii) Bus Topology

OR (2)

(i) VoIP (Voice over Internet Protocol)

(ii) IRC (internet Relay Chat)


Q No. SECTION C (3 X 3 = 9) Marks

29. def countchar():

fname=”Book.txt”

count=0

c=raw_input(“Enter the character to be searched for: “)

with open(fname,’r’) as f:

for line in f:

for word in line:

for char in word:

if char.strip()==c:

count=count+1

print(“No: of occurrences of “,c,”= “,count) (3)

(½ mark for correct function header)


(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
(½ mark for splitting the text into words)
(1 mark for correctly displaying the desired count)
OR

23 | P a g e
def CountHisHer():
f=open(“Story.txt”,’r’)
for line in f:
wordlist=line.strip()
count=0
for w in wordlist:
words=word.split(“ “)
for w in words:
w=w.strip().lower()
if w==’his’ or w==’her’:
count+=1
if count==0:
print(“Not found in file”)
else:
print(“Count=”,count)
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
( ½ mark for splitting the text into words)
(1 mark for correctly displaying the desired count)

24 | P a g e
30. (I)
def push_item(ItemStack, new_item):
ItemStack.append(new_item)
(II)
def pop_item(ItemStack):
if not ItemStack:
print("Underflow")
else:
return(ItemStack.pop())
(III)
def peep(ItemStack):
if not ItemStack:
print("None")
else:
print(ItemStack.peek())
(3x1 mark for correct function body; No marks for any function header as it
was a part of the question)
OR

def div_5(N): (3)


FactNumbers = []
for num in N:
if num % 5 == 0:
FactNumbers.append(num)
return FactNumbers

def pop_div5():
if not FactNumbers:
print("Underflow")
else:
print(FactNumbers.pop())

def Disp_div5():
if not FactNumbers:
print("None")
else:
print(FactNumbers[-1])

VALUES = []

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

FactNumbers = div_5(VALUES)

25 | P a g e
pop_div5()

26 | P a g e
Disp_div5()

(1/2 for identifying numbers divisible by 5)


(1/2 mark for correctly adding data to stack)
(1/2 mark for correctly poping data on the stack and 1/2 mark for checking
condition)
(1/2 mark for correctly displaying the data with none)
(1/2 mark for function call statements)

31.
The output is:
The string is: wELCcME&Cc&jnv
The new string is: vjc&MCE
(3)

OR

(i) Output: N1S325


(ii) Output: J1V3N5

(1 1/2 mark for each correct line of output)

Q No. SECTION D (4 X 4 = 16) Marks

32. I. SELECT DEPNAME, DEPARTMENT.DepCode FROM EMPLOYEE,


DEPARTMENT WHERE EMPLOYEE. DepCode=DEPARTMENT. DepCode Order
by DepCode DESC;
II. Select AVG (Age) from EMPLOYEE WHERE DepCode=”103″;
III. SELECT DeptHead FROM DEPARTMENT WHERE Employee.
TName=“Sanjeev P” AND EMPLOYEE. DepCode= DEPARTMENT. DepCode;
IV. SELECT * from EMPLOYEE WHERE joinDate<‟01-JAN-2007′;
(4)
(4 x 1 mark for each correct query)

OR
i) COUNT(DISTINCT DepCode) : 4
ii) Max (JoinDate) : 03 Mar-2010
Min (JoinDate) : 12-Jul-2004

27 | P a g e
iii)
TName DepHead
Sameer Sharma Ajay Dutta
RaguvindraK | Rajiv Kumar
Rama Gupta Yogesh Kumar
CR Menon PK Singh
Rajesh Kumar Yogesh Kumar
Sanjeev P Rajiv Kumar
Pragya Jain Ajay Dutta

iv) 5
(4 x 1 mark for each correct query output)

28 | P a g e
33.
import pickle
def countrec():
fobj=open(“bus.dat”,”rb”)
num=0
try:
while True:
rec=pickle.load(fobj)
if rec[2]==”Cochin” or rec[2]==”cochin”:
num+=1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() (4)
print(n)

(1 mark for opening in the file in right mode)


(1 mark for correctly creating the file object)
(1 mark for correctly checking the condition)
(1 mark for correctly displaying the records)
OR
def countrec():
num=0
fobj=open(“Salary.dat”,”rb”)
try:
print(“Emp ID\tEmp Name\tEmp Sal”)
while True:
rec=pickle.load(fobj)
if(re[2]>20000 and rec[2]<50000):
print(rec[0],”\t”,rec[1],”\t”,rec[2]”)
except:
fobj.close()

(1 mark for opening in the file in right mode)


(1 mark for correctly creating the file object)
(1 mark for correctly checking the condition)
(1 mark for correctly displaying the records)
Note (for both parts (I) and (II)):
(i) Ignore import csv as it may be considered the part of the
complete program, and there is no need to import it in individual
functions.
(ii) Ignore next(records, None) as the file may or may
not have the Header Row.

29 | P a g e
34. (A)
i) Select Name from SPORTS where Grade1=‟A‟ OR Grade2=‟A‟;
ii)Select count(*) from SPORTS group by GAME1 having GRADE1=‟A‟;
iii)Select Name from SPORTS where Game1=Game2;
iv)Select Game1,Game2 from SPORTS where Name LIKE „A%‟;

(4x1 mark for each correct query) (4)


OR
(B)
i)6
ii)4
iii)10
iv)2 2 1 1
(4x1 mark for each correct query output)

35. import mysql.connector as pymysql


dbcon=pymysql.connect(host=”localhost”, user=”root”, passwd=”sia@1928”)
if dbcon.isconnected()==False
print(“Error in establishing connection:”)
cur=dbcon.cursor()
query=”select * from stmaster”
cur.execute(query)
(4)
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.close()

(4x1 mark for each correct statement filled)

30 | P a g e
Q No. SECTION E (2 X 5 = 10) Marks
36. i) Human Resource (5)
ii)

(or Any other correct layout)


iii) Satellite Link
iv) Switch
v) Linux, Ubuntu, Open Solaris or any other Open Source O/s

(1 mark for each correct answer)

I. Option b / SNO
37.
II. Option c / The entire content
III. Option b / It will create an error
IV. Option b / next(fobj)
V. Option b / f.close() (5)

(1 mark for each correct answer)

31 | P a g e
NAVODAYA VIDYALAYA SAMITI, SHILLONG REGION
CLASS XII - COMPUTER SCIENCE (Code No: 083)
QUESTION BANK 2024-25
TOPIC: PYTHON REVISION TOUR – I & II
SECTION – A
1. Find the invalid identifier from the following:
a. True
b. true
c. Name
d. _12name
2. Which of the following symbol is used in Python for single line comment?
a. /
b. //
c. #
d. /*
3. Find the valid identifier from the following:
a. False
b. break
c. 21num
d. Num_12
4. Evaluate the following expression and identify the correct answer:
16 + 4 * (5 – 1) ** 2 / 4
a. 35
b. 35.0
c. 32.0
d. 32
5. Which of the following is valid arithmetic operator in Python?
a. //
b. &
c. <
d. =
6. What is the output of : 0.01 + 0.02 = = 0.03?
a. True
b. False
c. Error
d. Machine dependent
7. Which of the following is true for variable names in Python?

32 | P a g e
a. Unlimited length
b. All variables must have leading and trailing underscores
c. Underscore and ampersand are the only two special characters allowed
d. None of the mentioned
8. Which one among the following statements is True?
a. int (23.5) = =24
b. round (23.5) ==24
c. math.floor (23.5) ==24
d. math.fabs (23.5) ==24

9. Which of the following statement is True?


a. In a nested loop, a break statement terminates all the nested loops in one go
b. Python loops cannot have else clause
c. In Python, only if statement has else clause
d. The for loop is a counting loop and while is a conditional loop
10. What will be the output of the following expression?
(6<18) or (5<10) and (3<18) and not (8<18)
a. True
b. False
c. Syntax Error
d. None of the above
11. Given the Python declaration S1=”Hello World”. Which of the following statements will
give an error?
a. print(S1[4])
b. S2=S1
c. S3=S1[4:9])
d. S1[4]=”Y”
12. Give the output of the following:
x=5
x+=x-x
print(x)
a. 5
b. -5
c. 0
d. 10

13. The ……….. statement terminates the execution of the whole loop

33 | P a g e
a. continue
b. break
c. exit
d. jump
14. Which term describes a loop that continues repeating without a terminating condition?
a. Conditional loop
b. Uncontrolled loop
c. Infinite loop
d. Unlimited loop
15. To access a list which contains 10 elements, which of the following uses of range() would
produce a list of the desired indexes?
a. range(1,10)
b. range(10)
c. range(0,9)
d. range(1,11)
16. What is the output of the following Python statements?
x=2
while x <= 9:
print(x, end=’’)
x=x+1
a. 12345678
b. 2345678
c. 123456789
d. 23456789
17. What is the output of the following Python statements?
b=1
for a in range(1,10,2):
b += a + 2
print(b)
a. 31
b. 33
c. 36
d. 39
18. What will be the output of the following code:
x=12
for i in x:
print(i)

34 | P a g e
a. 12
b. 1 2
c. Error
d. None of the above
19. Write the output of the following statements:
x,y,z=2,3,2
z=y+x-2
y=z-x
print(“Z=”,z)
print(“Y=”,y)
a. Z 3
Y1
b. Z=3
Y=1
c. Z=3
Y=0
d. Z=0
Y=0
20. How many times is the following loop executed?
for a in range(100,10,-10):
print(a)
a. 10
b. 9
c. 1
d. 0
21. Which of the following output will never be obtained when the given code is executed?
import random
Shuffle = random.randrange(10)+1
Draw = 10*random.randrange(5)
print ("Shuffle", Shuffle, end="#")
print ("Draw", Draw)
a. Shuffle 1 # Draw 0
b. Shuffle 10 # Draw 10
c. Shuffle 10 # Draw 0
d. Shuffle 11 # Draw 50

22. For the following Python statements:

35 | P a g e
X= (2)
print(type(X))
What shall be the type of X?
a. Integer
b. String
c. Tuple
d. List
23. Study the following program and select the possible output from the options following it.
import random
x=random.random()
y=random.randint(0,4)
print(int(x),”:”,y+int(x))
a. 1:4
b. 0:0
c. 2:6
d. 0:5
24. Which keyword is used to create an alias name while importing a module in Python?
a. alias
b. as
c. with
d. from
25. Predict the output of the following Python statements:
>>>import statistics as s
>>>s.mode((1,2,1,2,3,2,1,4,4,1,2,3,2))
a. 1
b. 2
c. 3
d. 4
26. Given the following dictionary:
month = {1:"January", 2: "February", 3: "March", 4:"April", 5:"May"}
Which statement will return "March"?
a. month.pop()
b. month.pop(2)
c. month.pop(3)
d. month.pop(“March”)

27. Which of the following statement(s) would give an error after executing

36 | P a g e
the following code?
S="Happy" # Statement 1
print(S*2) # Statement 2
S+="Independence" # Statement 3
S.append("Day") # Statement 4
print(S) # Statement 5
a. Statement 2
b. Statement 3
c. Statement 4
d. Statements 3 and 4
Questions No.28, 29 and 30 are Assertion and Reason type questions. Each question
consists of two statements, namely, Assertion (A) and Reason (R).
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.
28. Assertion (A): In Python, tuple is an immutable sequence of data.
Reasoning (R): Immutable means that any change or alteration in data is mentioned in
the same place. The updated collection will use the same address for its storage.
29. Consider the given two statements:
Statement 1: t1 = tuple('python')
Statement 2: t1[4] = 'z'
Assertion (A): The above code will generate an error.
Reasoning (R): Tuple is immutable by nature.
30. Assertion (A): Keys of the dictionaries must be unique.
Reasoning (R): The keys of a dictionary can be accessed using values.
SECTION – B
31. Write the output displayed on execution of the following Python code:
H=["Aravalli","Nilgiri","Shivalik","Udaigiri"]
D={}
for S in H:
if len(S)%4 == 0:
D[S]= len(S)
for K in D:
print(K,D[K],sep="#")

37 | P a g e
32. Ashok, a Python programmer, is working on a project in which he wants to write a
method to count the number of even and odd values in the list. He has written the
following code but his code is having errors. Rewrite the correct code and underline the
corrections made.
L={12,23,43,36,48,75,50}
even_no=odd_no=0
for i in range(0, len(L))
if L[i]%2=0:
even_no+=1
Else:
odd_no+=1
print(even_no, odd_no)
33. (a) Given is a Python string declaration:
NAME = "Learning Python is Fun"
Write the output of :
print(NAME[-3:-13:-2])
(b) Write the output of the code given below:
dict1={1:["Rohit",20], 2:["Siya",90]}
dict2={1:["Rahul",95], 5:["Rajan",80]}
dict1.update(dict2)
print(dict1.values())
34. What will be the output of the following code, if the input is:
(i) abacacba (ii) bccaabaab
string=input("Enter a string:\n")
count=0
while True:
if string[0]=='a':
string=string[2:]
count+=1
elif string[-1]=='b':
string=string[:2]
count+=1
else:
break
print(string)
print(count)

38 | P a g e
35. Write a Python program to search for TName from a list of Teachers, and display
the position of its presence.
For example :
If the Teachers contain ["Ankit", "Siddharth", "Rohit","Sangeeta", "rohit"]
and TName contains "Rohit", The function should display:
Rohit at 2
rohit at 4
36. Predict the output of the following code :
d={"IND":"DEL","SRI”:"COL","CHI":"BEI"}
str1=""
for i in d:
str1=strl+str(d[i])+"@"
str2=str1[:–1]
print (str2)
37. Write the Python statement for each of the following tasks using BUILT-IN
functions/methods only :
(i) To delete an element 10 from the list lst.
(ii) To replace the string "This" with "That" in the string str1.
38. A dictionary dict2 is copied into the dictionary dict1 such that the common key’s
value gets updated. Write the Python commands to do the task and after that empty
the dictionary dict1.
39. Find the errors and describe the errors in each statements.
T1=(10,20,30,40,50,60,70,80,90)
T2=(1,2,3,4,5,6,7,8,9)
T3=T1*T2
print(T5[1:5:2])
L=T1.len()
print[T1,L]
40. Write the output on execution of the following Python code:
S="Do It Mom Yourself@2024"
L=S.split()
for W in L:
x = W.upper()
if (x = = x[::-1] ):
for I in x:
print(I,end="*")
else:

39 | P a g e
for I in W:
print(I,end="#")
print()
SECTION – C
41. Write a method in Python to display the elements of list thrice if it is a number and
display the element twice separated with ‘#’ if it is not a number.
For example, if the content of list is as follows:
ls = ["COMPUTER",12,"PENDRIVE",23,45,"KEYBOARD"]
The output should be:
COMPUTER#COMPUTER
121212
PENDRIVE#PENDRIVE
232323
454545
KEYBOARD#KEYBOARD
42. Write a program that takes a string with multiple words and capitalizes the first letter of
each word and forms a new string out of it where each word end with ‘$’.
For example, if the string is:
Str = “jawahar navodaya vidyalaya”
The output should be:
NewStr = “Jawahar$Navodaya$Vidyalaya$”
43. Predict the output of the following code :
def Find_Tot( Num = 10):
Sum=0
for C in range(1,Num+1):
if C % 2 != 0:
continue
Sum += C
return Sum
print(Find_Tot(5),end = "$")
print(Find_Tot(),sep = "@")
44. Predict the output of the Python code given below:
Text1 = "INDIA_G20"
Text2 = ""
I=0
while I < len(Text1):
if Text1[I] >= "0" and Text1[I] <= "9":

40 | P a g e
Val=int(Text1[I])
Val=Val+1
Text2 += str(Val)
elif Text1[I] >= "A" and Text1[I] <= "Z":
Text2 += Text1[I+1]
else:
Text2 += "*"
I += 1
print(Text2)
45. Predict the output of the code given below for the following inputs:
(i) NVS@24 (ii) jnv_N1
mystr = input("Enter a string:\n")
newstr = ""
count=0
for i in mystr:
if count % 2 != 0:
newstr = newstr + str(count)
else:
if i.lower():
newstr = newstr + i.upper()
else:
newstr = newstr + i
count += 1
print(newstr)
46. Write a program in Python where Sitem is a dictionary containing the details of computer
items – {Sname:Price}.
The program should insert the names of those items in to a list who have price greater
than 75. Also display the count of items inserted into the list.
For example:
If the dictionary contains the following data:
Ditem = {“Mouse”:140, “Keyboard”:35, “Monitor”: 18, “Camera”: 95}
The list should contain:
Mouse
Camera
The output should be:
The count of elements in the list is 2

41 | P a g e
47. Write the output of the code given below:
d = {"Jasmine": 15, "Rose": 7, "Tulip": 10, "Marigold": 25}
str1 = ""
for key in d:
if(d[key]>=10):
str1 = str1 + key + "@" + "\n"
str2 = str1[::-1]
print(str2)

48. Predict the output of the following code:


line=[5,10,15,20,25,30]
for I in line:
for j in range(1,I//5):
print(j,'*',end="")
print()
49. Predict the output of the code given below:
s="Welcome2cs@JNV"
n=len(s)
m=""
for i in range(0,n):
if(s[i]>='a' and s[i]<='m'):
m+=s[i].upper()
elif(s[i]>='n' and s[i]<='z'):
m+=s[i-1]
elif(s[i].isupper()):
m+=s[i].lower()
else:
m+='&'
print("The string is: ",m)
print("The new string is: ",m[::-2])
50. Consider the following code:
import random as ran
AR=[20, 30, 40, 50, 60, 70, 80]
lower = ran.randint(1, 3)
upper = ran.randint(2, 4)
for k in range(lower, upper + 1):
print(AR[k], end = " # ")

42 | P a g e
What possible output(s) are expected to be displayed on the screen at the time of
execution of the program from the following code? Also, specify the Minimum and
Maximum values that can be assigned to each of the variables lower and upper.
a. 20#30#40#
b. 30#40#
c. 50#60#70#
d. 70#80#

ANSWERS
SECTION – A
1. Option a
2. Option c
3. Option d
4. Option c
5. Option a
6. Option a
7. Option a
8. Option b
9. Option d
10. Option a
11. Option d
12. Option a
13. Option b
14. Option c
15. Option b
16. Option d
17. Option c
18. Option c
19. Option b
20. Option b
21. Option d
22. Option a
23. Option b
24. Option b
25. Option b
26. Option c

43 | P a g e
27. Option c
28. Option c - (A) is true but (R) is false
Explanation
In Python, tuples are immutable or unmodifiable, so once a tuple is created, we cannot
add, change, or update its elements.
29. Option a - Both A and R are true and R is the correct explanation of A.
Explanation
The statement t1 = tuple('python') creates a tuple t1 from the string 'python', resulting
in t1 being ('p', 'y', 't', 'h', 'o', 'n'). The statement t1[4] = 'z' attempts to modify the element
at index 4 of the tuple, which is not allowed because tuples are immutable in Python.
Hence, it raises an error.
30. Option c - A is true but R is false.
Explanation
The keys of dictionaries in Python must be unique and immutable. Values in a dictionary
can be accessed using their corresponding keys.
31. Output is:
Aravalli#8
Shivalik#8
Udaigiri#8
32. L=[12,23,43,36,48,75,50]
even_no=odd_no=0
for i in range(0, len(L)):
if L[i]%2==0:
even_no+=1
else:
odd_no+=1
print(even_no, odd_no)
33. (a) Output is: Fs ot
(b) Output is: dict_values ([['Rahul', 95], ['Siya', 90], ['Rajan', 80]])
34. (i) Enter a string:
abacacba
ba
3
(ii) Enter a string:
bccaabaab
bc
1

44 | P a g e
35. def search_teacher(teachers, TName):
TName = TName.lower()
for i in range(len(teachers)):
if teachers[i].lower() == TName:
print(f"{teachers[i]} at {i}")
teachers = ["Ankit", "Siddharth", "Rohit", "Sangeeta", "rohit"]
TName = "Rohit"
search_teacher(teachers, TName)
36. Output is: @IEB@LOC@LED
37. (i) lst.remove(10)
(ii) str1 = str1.replace("This", "That")
38.
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 20, 'c': 30, 'd': 40}
dict1.update(dict2)
print("Updated dict1:", dict1)
dict1.clear()
print("dict1 after clearing:", dict1)

39. T1=(10,20,30,40,50,60,70,80,90)
T2=(1,2,3,4,5,6,7,8,9)
T3=T1*T2 #Error1 – T1*T2 can't multiply
print(T5[1:5:2]) #Error2 – T5 is not defined
L=T1.len() #Error3 – len() is used wrongly
print[T1,L] #Error4 – Syntax of print is wrong
40. The output is: M*O*M*Y#o#u#r#s#e#l#f#@#2#0#2#4#
41. The method in Python is:
ls = ["COMPUTER",12,"PENDRIVE",23,45,"KEYBOARD"]
for s in ls:
s=str(s)
if s.isalpha():
print(s,s,sep="#")
if s.isdigit():
print(s*3)

42. Str = input(“Enter a string:”)


new_words = [word.capitalize() + '$' for word in Str.split()]

45 | P a g e
NewStr = ''.join(new_words)
print("NewStr =", NewStr)
or
str=input("Enter a string:\n")
newstr=""
lstr=str.split()
for i in lstr:
newstr+=i.capitalize()
newstr+='$'
print("The new string is:\n",newstr)

43. Ouput : 6$30

44. The output is: NDIA_*231

45. (i) Output: N1S325


(ii) Output: J1V3N5
46.
Ditem = {"Mouse": 140, "Keyboard": 35, "Monitor": 18, "Camera": 95}
items_over_75 = []
for item, price in Ditem.items():
if price > 75:
items_over_75.append(item)
for item in items_over_75:
print(item)
c=len(itemsover_75)
print("The count of elements in the list is: ",c)
47. The output is:
@dlogiraM
@piluT
@enimsaJ
48. The ouput is:
1*
1 *2 *
1 *2 *3 *
1 *2 *3 *4 *
1 *2 *3 *4 *5 *

46 | P a g e
49. The output is:
The string is: wELCcME&Cc&jnv
The new string is: vjc&MCE

50. Option b
lower :- Minimum Value = 1, Maximum Value = 3
upper :- Minimum Value = 2, Maximum Value = 4

47 | P a g e
PRACTICE QUESTION PAPER (THEORY)
CLASS: XII SESSION: 2024-25
COMPUTER SCIENCE (083)
Time allowed: 3 Hours Maximum Marks: 70
General Instructions:
This question paper contains 37 questions.
All questions are compulsory. However, internal choices have been provided in
some questions. Attempt only one of the choices in such questions
The paper is divided into 5 Sections- A, B, C, D and E.
Section A consists of 21 questions (1 to 21). Each question carries 1 Mark.
Section B consists of 7 questions (22 to 28). Each question carries 2 Marks.
Section C consists of 3 questions (29 to 31). Each question carries 3 Marks.
Section D consists of 4 questions (32 to 35). Each question carries 4 Marks.
Section E consists of 2 questions (36 to 37). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
In case of MCQ, text of the correct answer should also be written.

Q Section-A (21 x 1 = 21 Marks) Marks


No.
1
1- Find the valid identifier from the following 1
(a) Total_ (b) TRUE (c) 4thdata (d) break 1
1
1
Suppose a tuple T is declared as T=(11,22,33)
and a list L
2 Suppose a tuple T is declared as T=(11,22,33) and a list L=["orange", "blue", "red", , 1
which of
the following is incorrect ?
a) min(L)
b) L[1] = ‘green’
c) T[0] = 15
d) print( min(T))

3 Which of the following is a DML command ? 1


(a) DROP (b) INSERT (c) ALTER (d) CREATE
4 1
Given a string S = “Himalayan valley”, write the
output of
print(S[-1: :-1])
5 An attack that encrypts files in a computer and only gets decrypted after 1
paying money to the attacker.
a) Botnet b) Trojan c) Ransomware d) Spam
6 Which of the following is not an integrity constraint? 1
a) Not null
b) Composite key
c) Check constraint
d) Primary Key

48 | P a g e
7 To read the next line of the file from a file object fobj, we 1
use
(a) fobj.read(all) (b) fobj.read() (c) fobj.readline() (d)
fobj.readlines()
8 The where and Having clauses can be used interchangeably in SELECT 1
queries
(a) True (b) False (c) Only in views (d) with order by
9 Sita used a pen drive to copy files from his friend’s laptop to his office 1
computer. Soon his computer started abnormal functioning. Sometimes it
would restart by itself and sometimes it would stop different applications
running on it.
Which of the following options out of (i) to (iv), would have caused the
malfunctioning of the computer? Justify the reason for your chosen option.
(i) Computer Virus (ii) Spam Mail (iii) Computer Bacteria (iv) Trojan Horse
10 Which of the following is not a network device 1
(i) Firewall (ii) Router (iii) Bridge (iv) Gatway
11 For a binary file seek() method accepts: 1
a) Exactly one Parameter
b) Exactly Two Parameter
c) At most one Parameter
d) At most one Parameter

12 Which of the following statements is correct regarding file access modes? 1


(a) In ‘r’ mode, we can read and write data from/in the file.
(b) In ‘a’ mode, the existing data will be over-written if the file exists.
(c) In ‘w’ mode, the data in the file is retained and new data will be appended
to the end.
(c) In ‘a+’ mode, both reading and writing operations can take place and new
data is appended to the end of the existing file

.
13 1
Which of the following options can be used to read the first five characters
of a text file ‘Poem.txt’ from the file object File1?
(a) File1.read(4) (b) File1.readlines(5)
(c) File1.read(5) (d) File1.read(6)
14 Consider a function 1
def Cal_cube(n):
Which of the following function call can be used to invoke the given function
definition?
(a) Calc_cube(5): (b) Calc_cube()
(c) Calc_cube(5) (d) Calc_cube(5,5,5)

15 A variable created or define within a function body is classified as: 1


a) local (b) global (c) built-in (d) instance
16 The process of removing an element from stack is called 1
a) Delete (b) remove(c) push (d) pop
17 _________ ia a communaction methodology designed to deliver booth voice 1
and multimedia communication over internet protocol.
a) Voip (b) SMTP (c) PPP (d) HTTP

49 | P a g e
18 Which command is used for cleaning up the environment 1
a) my.closed()(b) is.end()(c) con.quit() (d) mycon.close()
19 The function is used to display the total no of records from the table in 1
database
a) sum(*) (b) Total(*)(c) count(*) (d) All
Q20 and Q21 are Assertion(A) and Reason(R) 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-(D) A is False but R is True

20 Assertion(A): [1, 2,3] ia an invalid key for a dictionary in python 1


Reason (R ) Only number and string can be the keys of a dictionary in python

21 Assertion(A): CSV(Comma separated values) is a file format for data storage 1


which looks like a text file.
Reason (R ) The information is organized with one record on each line and
field is separated by semicolon.

Q Section-B (7 x 2 = 14 Marks) Marks


No.
22 2
What is the difference between hub and switch? Which is more preferable in
a large network of computers and why?

23 Rahul has written a code to input a number and return its reverse. His code is 2
having errors. Rewrite the correct code and underline the corrections made.
def reverse()
n=int(input("Enter number :: ")
rev=0
while(num>0):
r=num%10
rev=rev*10+r
num=num//10
return rev
24 Write the output of the code givenbelow: 2
dictcount={“age1”:26,”age2”:32,”age3”:40}
sum=0
for key in dictcount:
sum=sum+dictcount[key]
print(sum)
25 Predict the output of the Python code given below: 2
def product(L1,L2):
p=0
for i in L1:
for j in L2:
p=p+i*j
return p
LIST=[1,2,3,4,5,6]
l1=[]
l2=[]

50 | P a g e
for i in LIST:
if(i%2==0):
l1.append(i)
else:
l2.append(i)
print(product(l1,l2))

OR
Predict the output of the Python code given below:
tuple1 = (33, 24, 44, 42, 54 ,65)
list1 =list(tuple1)
new_list = []
for i in list1:
if i>40:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
26 What will be the output of the following code? 2
import random
color = ['Red', 'Orange', 'Yellow', 'Black', 'Cyan']
for c in range(len(color)):
p = random.randint(2,4)
print(color[p],end='$')

or
What will be the output of the following code?
def Sum():
global p
p=p+7**2
print(p, end= '#')
p = 10
print(p,end= '@')
Sum()
print(p)
27 Differentiate between Where and Having clause in SQL with example. 2

OR
Define aggregate function and give example.

28 Write two points of difference between Circuit Switching and Packet 2


Switching
OR
Write two points of difference between XML and HTML.

Q Section-C (3 x 3 = 9Marks) Marks


No.
29 Each node of a STACK contains the following information. 3
(i) Pin code of a city (ii) name of the city

Write a program to implement the following operations in the above STACK


PUSH ( ) – to push a node in the stack
POP ( ) – to remove a node from the stack
OR
Vikram has a list containing 10 integers. You need to help him to create a
program with separate user defined functions to perform the following

51 | P a g e
operations based on this list.
● Traverse the content of the list and push the numbers that are divisible by 5
into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
1055 35
30 Write a method beginA() in Python to read lines from a text file 3

Notebook.TXT, and
display those lines, which are starting with ‘A’.
For 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 beginA() function should display the output as:
An apple a day keeps the doctor away.
A marked difference will come in our country.
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.

31 3

What will be the output of the following program


a-
fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]

fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'

sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':

52 | P a g e
sum += 1
if ls[1] == 'Kiwi':
sum += 20

print (sum)

b- x=[6,12,13,24,30]
for i in x;
for j in range( 1,i%4):
print(j, end= ‘ ‘)
print ( )

SECTION D(4*4=16)

32 Write SQL commands for (a) to (e) on the basis of table GRADUATE 4

TABLE- GRADUATE

AVERAGR
SR_NO NAME STIPEND SUBJECT MARK DIV
1 KARAN 400 PHYSICS 68 1
2 DIVAKAR 450 COMPUTER CS 68 1
3 DIVYA 300 CHEMISTRY 62 2
4 ARUN 350 PHYSICS 63 1
5 SABINA 500 MATHEMATICS 70 1
6 JOHN 400 CHEMISTRY 55 2
7 ROBERT 250 PHYSICS 64 1
8 RUBINA 450 MATHEMATICS 68 1
9 VIKAS 500 COMPUTER CS 62 1
10 MOHAN 300 MATHEMATICS 57 2

a)List the names of those students who have obtained DIV 1 sorted by
NAME.

(b) Display a report, listing NAME, STIPEND, SUBJECT and amount of


stipend
received in a year assuming that the STIPEND is paid every month.

53 | P a g e
(c) To count the number of students who are either PHYSICS or COMPUTER
SC graduates.

(d) To insert a new row in the GRADUATE table:


11,”KAJOL”,300 , “COMPUTER SC”, 75,1

(e) Display Name of the students whose average is more than 65.

33 A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. 4

1. Write a user defined function CreateFile() to input data for a record and add to
Book.dat .
2.
2. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in the
binary file “Book.dat

34 Consider the tables Watches and Sale given below and answer the following 4
questions.
Table- Watches

Watchid Watch_Name Price Type Qty_Store


W001 High Time 10000 Unisex 100
W002 Life Time 15000 Ladies 150
W003 Wave 20000 Gents 200
W004 High Fashion 7000 Unisex 250
W005 Golden Time 25000 Gents 100

Table-Sale

Watchid Qty_Sold Quarter


W001 10 1
W003 5 1
W002 20 2
W003 10 2
W001 15 3
W002 20 3
W005 10 4
W003 15 4

a-To display total quantity in store of unisex type watches.

b- To display watch name and their quantity sold in first quarter.

54 | P a g e
c- To display watch name ,price and type from the table Watches and
sale with their correspond watchid.
d- To display watch name, Qty_store and total quantity sold from table
Watches and Sales of each watchid .

35 GNES Public School is managing student data in a ‘Student’ Table in ‘ 4

School’ Database . Write a Python code that connect to database school


and retrieve all records and display total no of students.
SECTION E(2*5=10)
36 Write a function in python to search and display details, whose destination is “Cochin” 5
from binary file “Bus.Dat”. Assuming the binary file is containing the following elements
in the list:
1. Bus Number
2. Bus Starting Point
3. Bus Destination

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

BUSINESS TECHNOLOGY
BLOCK BLOCK

LAW BLOCK HR CENTRE

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


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

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

Law block 15
Technology block 40
HR Centre 115
Business block 25

(a) Suggest a cable layout of connection between the blocks.

(b) Suggest the most suitable place to house the server of the organization with
suitable reason.

(c) Which device should be placed/ installed in each of these blocks to efficiently
connect all the computers within these blocks?

55 | P a g e
(d) The university is planning to link its sales counters situated in various parts of
the CITY. Which type of network out of LAN, MAN or WAN will be formed?

(e) Which network topology may be preferred between these blocks?

56 | P a g e
Subject- Computer Science Max marks = 70
Marking scheme

Section- A

Question No Answer Marks


1-A) Total_ C)- TRUE
1 1
C- T[0]=15 1
2
B-) Insert 1
3
yellav nayalamih 1
4
C-) Ransomware 1
5
B)- Composite Key 1
6
C)- fobj.readline( ) 1
7
B)- False 1
8
A)- computer virus 1
9
A)- Firawall 1
10
B)- Exatly two pairs 1
11
D)- 1
12
C)- File1.read( 5) 1
13
C)- calc_ cube(5) 1
14
A)- local 1
15
D)- pop 1
16
A)- Voip 1
17
D)- mycon.close() 1
18
C)-count( *) 1
19
C- A is True But R is false 1
20
C- A is True But R is false 1
21

57 | P a g e
Section B

22-Hub forwards the message to every node connected and create a huge traffic in the network hence
reduces efficiency whereas a Switch is also called intelligent hub since it redirects the received
information/ packet to the intended node(s). In a large network a switch is preferred to reduce the
unwanted traffic in the network which may also reduce the bandwidth and cause network congestion .

23-ANS:
def reverse():
n=int(input("Enter number :: ")
rev=0
while(num>0):
r=num%10
rev=rev*10+r
num=num//10
return rev

24- Output- 98

25- Output- 108 OR (44.42,54,65)

26- Cyan$Black$Black$Cyan$Yellow$ OR 10@59#59

27- where and having clause

Aggregate function with exm.

28-

Ans: Circuit Switching Packet Switching

Circuit switching is the method of Packet switching is the method of


switching which is used for switching where no dedicated path
establishing a dedicated is established from the source to the
communication path between the destination.
sender and the receiver.
Data is processed and transmitted Data is processed and transmitted,
at the source only. not only at the source but at each
switching station.
It is more reliable. It is less reliable.

OR

XML (Extensible MarkupLangauge)

HTML (Hypertext Markup Langauge)


-defined and it is a markup language

58 | P a g e
Section C
29-
Each node of a STACK contains the following information.
(i) Pin code of a city (ii) name of the city
Write a program to implement the following operations in the above STACK

PUSH ( ) – to push a node in the stack


POP ( ) – to remove a node from the stack and print

STK = [ ]
def PUSH (stk, val) :
stk.append(val)
def POP(stk):
if stk != []:
return stk.pop( )
else:
return None
for i in stk :
print(i)
while True:
if STK != []:
print(POP(STK),end=" ")

else:
break
string=input("enter city and pincode").split()
print(string)
for I in string:
PUSH(STK,I)
POP(STK)
1 mark for correct PUSH operation
1 mark for correct POP operation
1 mark for correct function calls and displaying the output

OR

N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[ ]
for k in N:
if k%2==1: #or if k%2:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST),end=" ")
else:
break
1 mark for correct PUSH operation
1 mark for correct POP operation
1 mark for correct function calls and displaying the output

59 | P a g e
30-- Ans:
def beginA():
f=open(‘Notebook.TXT’)
l=f.readlines()
for i in l:
if i[0]==’A’ or i[0]= =’a’:
#or if i[0] in [“A”,”a’]
print(i)
f.close()
OR
fr=open(“PYTHON.TXT”)
fw=open(“PYTHON1.TXT”, ‘w’)
d=fr.read()
for i in d:
if not i.isdigit():
fw.write(i)
fr.close()
fw.close()

31-Output- 22

OR….

1#
1#
1#
32- 1.(a) Select Name From GRADUATE Where DIV = 1 Order by Name;
(b) Select Name, stipend, subject, stepend *12 From GRADUATE
(c) Select count (*) From GRADUATE Where subject IN(“PHYSICS”,”COMPUTER SC”);
(d) Insert into GRADUATE Values (11,”KAJOL”, 300,”COMPUTER SC”,75,1);
(e ) Select name from Graduate where average>65

33- import pickle

def createfile():

fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()
createfile()

def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1

60 | P a g e
print(rec[0],rec[1],rec[2],rec[3])
except:
fobj.close()
rteurn num

n=countrec("amit")

print(“Total record”,n)

34--

i- SELECT SUM(QTY_STORE) FROM WATCHES WHERE TYPE =’Unisex’;

ii
SELECT WATCH_NAME, QTY_SOLD FROM WATCHES W, SALE S WHERE
S.WATCHID=S.WATCHID AND QUARTER=1;

iii- SELECT WATCH_NAME, PRICE , TYPE FROM WATCHES W, SALE S WHERE


W.WATCHID=S.WATCHID;

iv- SELECT WATCH_NAME, QTY_STORE , SUM(QTY_SOLD), FROM WATCHES W,


SALE S WHERE W.WATCHID = S.WATCHID GROUP BY S.WATCHID

35-

import mysql.connector
Con= mysql.connector.connect (host=”localhost”,user”root”, passwd=”1234’,database=”school”)
Cursor=cursor.cursor()
Cursor.execute(“select * from student”)
Rec=cursor=cursor.fetchall()
count=0
for i in rec;
count +=1
print(i)
print(“Total no of Records are”,count)
con.close()

36-import pickle
def countrec():
fobj=open("bus.dat","rb") num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1

61 | P a g e
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() # This function is called just to verify result

print(n)

37-(a) Suggest a cable layout of connection between the blocks.

BUSINESS TECHNOLOGY
BLOCK BLOCK

LAW BLOCK HR CENTRE

(b) Ans : HR centre because it consists of the maximum number of computers to house the server.

(c) Ans: Switch/ Hub should be placed in each of these blocks.

(d) Ans : MAN

(e) Ans : Bus

62 | P a g e
FUNCTION IN PYTHON
Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable
(global scope, local scope)
Let us revise
 A function is a block of code that performs a specific task.
 Advantages of function: Reusability of code, Reduce size of code, minimum number
of statements, minimum storage, Easy to manage and maintain
 Types of functions: Built-in-functions, Functions defined in module, User defined
function
 Built-in functions are the functions whose functionality is pre-defined in python like
abs(), eval(), input(), print(), pow()
 Some functions are defined inside the module like load() and dump() function defined
inside the pickle module.
 A function that can be defined by the user is known as user defined function.
 def keyword is used to define a function.
 There is a colon at the end of def line, meaning it requires block
 User Defined function involved two steps:
defining
calling
 Syntax for user defined function:
def <function name>( [parameter list ]):
[””function’s doc string ””]
<statement>
[<statement>]
 Python supports three types of formal arguments/ parameters: Positional Arguments,
Default parameters, Keyword (or named ) Arguments
 Positional Arguments: When the function call statement must match the number and
order of arguments as defined in the function definition, this is called the positional
argument matching.
 A parameter having default value in the function header is known as a default
parameter.
 Keyword Arguments are the named arguments with assigned values being passed in
the function call statement.
 A function may or may not return one or more values.
 A function that does not return a value is known as void function and returns legal
empty value None.
 Functions returning value are also known as fruitful functions.
 The flow of execution refers to the order in which statements are executed during a
program.
 A variable declared in a function body (block) is said to have local scope. i.e. it can
be accessed within this function.
 A variable declared outside of all functions/top level of segment of a program is said
to have global scope. i.e. it can be accessible in whole program and all blocks (
functions and the other blocks contained within program.

63 | P a g e
MIND MAP ON FUNCTION
Function: A function is a group of statements that exists within a
program for the purpose of performing a specific task.

Types Scope: Scope of a variable is the area of the program


where it may be referenced.

Built-in-functions: User Defined


Bulit-in functions are Function defined in
module: A module is functions: A function
the predefined is a block of code which
functions that are a file containing
functions and only runs when it is
already available in called. In Python, a
variables defined in Local: A variable
the python. Ex- int(), function is defined
separate files. created inside a
using the def keyword. function belongs to
the local scope of
that function, and
can only be used
Global: A variable declared inside that function.
outside of all functions/top Ex-
level of segment of a program
is said to have global scope. i.e. x = 300
it can be accessible in whole def myfunc():
program and all blocks. print(x)
myfunc()
Ex- print(x)
def myfunc():
x = 300
print(x)
myfunc()

Types of Arguments/Parameters

Default Arguments: A Keyword Arguments:


Positional Arguments: default argument is an Value can be provided by using
argument that assumes a their name instead of the position
Arguments passed to a default value if a value is not
function in correct positional (order) in function call statement.
provided in the function call These are called keyword
order. for that argument. arguments.

64 | P a g e
Multiple Choice Questions (1 Mark)
1. What is the default return value for a function that does not return any value explicitly?
(a) None (b) int (c) double (d) null
2. Which of the following items are present in the function header?
(a) Function name only (b) Parameter list only
(c) Both function name and parameter list (d) return value
3. Which of the following keyword marks the beginning of the function block?
(a) func (b) define (c) def (d) function
4. Pick one of the following statements to correctly complete the function body in the given
code snippet.
def f(number):
# Missing function body
print (f(5))
(a) return “number” (b) print(number) (c) print(“number”) (d) return number
5. Which of the following function header is correct?
(a) def f(a=1,b): (b) def f(a=1,b,c=2):
(c) def f(a=1, b=1, c=2): (d) def f(a=1,b=1,c=2,d);
6. Which of the following statements is not true for parameter passing to functions?
(a) You can pass positional arguments in any order.
(b) You can pass keyword arguments in any order.
(c) You can call a function with positional and keyword arguments.
(d) Positional arguments must be before keyword arguments in a function call
7. A variable defined outside all the functions referred to as………..
(a) A static variable (b)A global variable (c) A local variable (d) An automatic variable
8. What is the order of resolving scope of a name in a python program?
(L: Local namespace, E: Enclosing namespace, B: Built-In namespace, G: Global namespace)
(a) BGEL (b) LEGB (c) GEBL (d) LBEG
9. Assertion (A):- If the arguments in a function call statement match the number and order
of arguments as defined in the function definition, such arguments are called positional
arguments.
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
(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
10. The.......................... refers to the order in which statements are executed during a program
run.
(a) Token (b) Flow of execution (c) Iteration (d) All of the above
11. Choose the correct option:
Statement1: Local Variables are accessible only within a function or block in which it is
declared.
Statement2: Global variables are accessible in the whole program.
(a) Statement1 is correct but Statement2 is incorrect
(b) Statement2 is correct but Statement1 is incorrect
(c) Both Statements are Correct
(d) Both Statements are incorrect
12. The............................. of a variable is the area of the program where it may be referenced
a) external b) global c) scope d) local

65 | P a g e
Answers
Questions Answers

1. (a) None
2. (c) Both function name and parameter list
3. (c) def
4. (d) return number
5. (c) def f(a=1, b=1, c=2):
6. (a) You can pass positional arguments in any order.
7. (b) A global variable
8. (b) LEGB
9. (c) A is True but R is False
10. (b) Flow of execution
11. (c) Both Statements are Correct
12. c) scope

Short Questions (2 Marks)


Q1. What do you mean by a function? How is it useful?
Answer: A function is a block of code that performs a specific task. Functions are useful
as they can be reused anywhere through their function call statements.
Q2. Observe the following Python code very carefully and rewrite it after removing all
syntactical errors with each correction underlined.
def execmain():
x = input("Enter a number:")
if (abs(x)= x):
print("You entered a positive number")
else:
x=*-1
print("Number made positive : ",x)
execmain()
Answer:
def execmain():
x = int(input("Enter a number:"))
if (abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive : ",x)
execmain()
Q3. What is an argument? Give an example.
Answer: An argument is data passed to a function through function call statement. It is
also called actual argument or actual parameter. For example, in the statement
print(math.sqrt(25)), the integer 25 is an argument.
Q4. What is the output of the program given below?
x = 75
def func (x) :
x = 10
func (x)
print ('x is now', x)
Answer: x is now 75
Q5. What will be the output of the following code:

66 | P a g e
total=0
def add(a,b):
global total
total=a+b
print(total)
add(6,6)
print(total)
Answer: 12
12
Q6. Is return statement optional? Compare and comment on the following two return
statements:
(i) return
(ii) return val
Answer: The return statement is optional only when the function does not return a value. A
function that returns a value must have at least one return statement.
From the given two return statements,
(i) The statement return is not returning any value. Rather it returns the control to
caller along with empty value None.
(ii) The statement return val is returning the control to caller along with the value
contained in variable val.
Q7. Divyansh, a python programmer, is working on a project which requires him to define a
function with name CalculateInterest(). He defines it as:
def CalculateInterest(Principal,Rate=.06, Time): # Code
But this code is not working, Can you help Divyansh to identify the error in the above
function and with the solution?
Answer. Yes, here non-default argument is followed by default argument which is wrong as
per python’s syntax. (while passing default arguments to a function ,all the arguments to its
right must also have default values, otherwise it will result in an error.)
Q8. Write a function that takes a positive integer and returns the one’s position digit of the
integer.
Answer: def getOnes(num):
oneDigit=num%10 # return the ones digit of the integer num
return oneDigit
Q9. Anita has written a code to input a number and check whether it is prime or not. His code
is having errors. Rewrite the correct code and underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
if n%i=0:
print("Number is not prime \n")
break
else:
print("Number is prime \n’)
Answer:
def prime():
n=int(input("Enter number to check :: ")) #bracket missing
for i in range (2, n//2):
if n%i==0: # = missing
print("Number is not prime \n")
break #wrong indent
else:
print("Number is prime \n”) # quote mismatch

67 | P a g e
Q10. What is the difference between parameter and argument?
Answer:
Parameters are temporary variable names within functions. The argument can be
thought of as the
value that is assigned to that temporary variable.
For instance, let’s consider the following simple function to calculate sum of two
numbers.
def sum(a,b):
return a+b
sum(10,20)
Here a, b are the parameters for the function ‘sum’. Arguments are used in procedure
calls, i.e., the values passed to the function at runtime.10, 20 are the arguments for the
function sum.
Q11. What is the significance of having functions in a program?
Answer: Creating functions in programs is very useful. It offers the following advantages:
(i) The program is easier to understand.
(ii) Redundant code is at one place, so making changes is easier.
(iii) Reusable functions can be put in a library in modules.
Q12. What is the difference between local variable and global variable? Also give a suitable
Python code
to illustrate both.
Answer:
S.No. Local Variable Global Variable
1. It is a variable which is declared within a It is a variable which is declared
function or within a block. outside all the functions or in a global
space.
2. It cannot be accessed outside the function It is accessible throughout the
but only within a function/block of a program in which it is declared.
program.
For example, in the following code x, xcubed are global variables and n and cn are local
variables.
def cube(n): # n and cn are local variables
cn=n*n*n
return cn
x=10 # x is a global variable
xcubed=cube(x) # xcubed is a global variable
print(x, “Cubed 15”, xcubed)

Short Questions (3 Marks)


Q1. Consider the following function that takes two positive integer parameters a and b.
Answer the following questions based on the code below:
def funct1(a,b):
if a>1:
if a%b==0:
print (b, end=’ ‘)
funct1(int(a/b),b)
else:
funct1(a,b+1)
(a) What will be printed by the fuction call funct1(24,2)?
(b) What will be printed by the fuction call funct1(84,2)?

68 | P a g e
(c) State in one line what funct1()is trying to calculate.
Answer (a) 2 2 2 3
(b) 2 2 3 7
(c) finding factors of A which are greater than and equal to B.
Q2. Write a user defined function to print the odd numbers from a given list passed as an
argument.
Sample list: [1,2,3,4,5,6,,7,8,9,10]
Expected Result: [1,3,5,7,9]
Answer:
def odd_num(l):
odd=[]
for n in l:
if n%2!=0:
odd.append(n)
return odd
print(odd_num([1,2,3,4,5,6,7,8,9,10]))
Q3. Which line in the given code(s) will not work and why?
def interest(p,r,t=7):
I=(p*r*t)
print(interest(20000,.08,15)) #line 1
print(interest(t=10, 20000, 0.75)) #line 2
print(interest(50000, 0.7)) #line 3
print(interest(p=10000,r=.06,time=8)) #line 4
print(interest(80000, t=10)) #line 5
Answer: Line 2: positional argument must not be followed by keyword argument, i.e.,
positional argument
must appear before a keyword argument.
Line 4: There is no keyword argument with name ‘time’
Line 5: Missing value for positional arguments, R.
Q4. Write a python function showlarge() that accepts a string as parameter and prints the
words whose length is more than 4 characters.
Eg: if the given string is “My life is for serving my Country”
The output should be
serving
Country
Answer:
def showlarge(s):
l = s.split()
for x in l:
if len(x)>4:
print(x)
s=" My life is for serving my Country "
showlarge(s)
Q5. Write a function Interchange (num) in Python, which accepts a list num of integers, and
interchanges the adjacent elements of the list and print the modified list as shown below:
(Number of elements in the list is assumed as even)
Original List: num = [5,7,9,11,13,15]
After Rearrangement num = [7,5,11,9,15,13]
Answer:
def Interchange(num):
for i in range(0,n,2):

69 | P a g e
num[i], num[i+1] = num[i+1], num[i]
print(num)
num=[5,7,9,11,13,15]
n=len(num)
if n%2==0:
Interchange(num)
Q6. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to
the 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]
Answer:
def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList

Long Questions/Case Study/Application Based (4 Marks)


Q1. Krishnav is looking for his dream job but has some restrictions. He loves Delhi and
would take a job there if he is paid over Rs.40,000 a month. He hates Chennai and
demands at least Rs. 1,00,000 to work there. In any another location he is willing to work
for Rs. 60,000 a month. The following code shows his basic strategy for evaluating a job
offer.
def DreamProject():
pay=
location=
if location == "Mumbai":
print ("I’ll take it!") #Statement 1
elif location == "Chennai":
if pay < 100000:
print ("No way") #Statement 2
else:
print("I am willing!") #Statement 3
elif location == "Delhi" and pay > 40000:
print("I am happy to join") #Statement 4
elif pay > 60000:
print("I accept the offer") #Statement 5
else:
print("No thanks, I can find something better") #Statement 6

On the basis of the above code, choose the right statement which will be executed when
different inputs for pay and location are given
(i) Input: location = “Chennai”, pay = 50000
a. Statement 1 b. Statement 2 c. Statement 3 d. Statement 4
(ii) Input: location = “Surat” ,pay = 50000
a. Statement 2 b. Statement 4 c. Statement 5 d. Statement 6
(iii) Input- location = “Any Other City”, pay = 1
a Statement 1 b. Statement 2 c. Statement 4 d. Statement 6

70 | P a g e
(iv) Input location = “Delhi”, pay = 500000
a. Statement 6 b. Statement 5 c. Statement 4 d. Statement 3

Answer: (i) b. Statement2 (ii) d. Statement6 (iii) d. Statement6 (iv) c. Statement4

Q2. Kids Elementary is a Playway school that focuses on “Play and learn” strategy that helps
toddlers understand concepts in a fun way. Being a senior programmer, you have taken
responsibility to develop a program using user-defined functions to help children differentiate
between upper case and lower case letters/ English alphabet in a given sequence. Make sure
that you perform a careful analysis of the type of alphabets and sentences that can be included
as per age and curriculum. Write a python program that accepts a string and calculates the
number of upper case letters and lower case letters.
Answer:
def string_test(s):
d={"UPPER_CASE":0,"LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print("Original String:",s)
print("No. of Upper Case Characters:",d["UPPER_CASE"])
print("No. of Lower Case Characters:",d["LOWER_CASE"])
string_test("Play Learn and Grow")

Case Based/ Source Based Integrated Questions (5 Marks)


Q1. Traffic accidents occur due to various reasons. While problems with roads or inadequate
safety facilities lead to some accidents, majority of the accidents are caused by driver’s
carelessness and their failure to abide by traffic rules.
ITS Roadwork is a company that deals with manufacturing and installation of traffic
lights so as to minimize the risk of accidents. Keeping in view the requirements, traffic
simulation is to be done. Write a program in python that simulates a traffic light. The
program should perform the following:
(a) A user defined function trafficLight() that accepts input from the user, displays an
error message if the following is displayed depending upon return value from
light(); [2]
(i) “STOP, Life is more important than speed”, if the value returned by
light() is 0.
(ii) “PLEASE GO SLOW”, if the value returned by light() is 1.
(iii) “You may go now”, if the value returned by light() is 2.
(b) A user defined function light() that accepts a string as input and returns 0 when
the input is RED, 1 when the input is YELLOW and 2 when the input is GREEN.
The input should be passed as an argument. [2]
(c) Display “BETTER LATE THAN NEVER” after the function trafficLight() is
executed. [1]
Answer: (a)
#Program to simulate a traffic light comprising of two user defined functions trafficLight() and
light()
def trafficLight():
signal=input("Enter the colour of the traffic light:")

71 | P a g e
if signal not in ["RED","YELLOW","GREEN"]:
print("Please enter a valid traffic light colour in CAPITALS")
else:
value=light(signal)
if value==0:
print("STOP","Life is more important thanspeed")
elif value==1:
print("PLEASE GO SLOW")
else:
print("You may go now")
(a) # function light()
def light(colour):
if colour=="RED":
return 0
elif colour=="YELLOW":
return 1
else:
return 2
trafficLight()

# Display BETTER LATE THAN NEVER


print("BETTER LATE THAN NEVER")

Q2. Observe the following code and select appropriate answers for the given questions:
total=1
def multiply(l): # line1
for x in l:
total # line2
total*=x
return # line3
l=[2,3,4]
print(multiply( ), end=” “) # line4
print(“ , Thank You”)
(i) Identify the part of function in # line1
(a) Function header (b) Function calling (c) Return statement (d)Default argument
(ii) Which of the keyword is used to fill in the blank for # line2 to run the program
without error.
(a) eval (b) def (c) global (d) return
(iii) Which variable is going to be returned in # line3
(a) total (b) x (c) l (d) None
(iv) Which variable is required in the # line4
(a) total (b) x (c) l (d) None
(v) In the # line4 the multiple(l) is called
(a) Caller (b) Called (c) Parameters (d) Arguments
Answer: (i) (a) Function header
(ii) (c) global
(iii) (a) total
(iv) (c) l
(v) (a) Caller

72 | P a g e
Exception Handling
Exception: Contradictory or Unexpected situation or unexpected error, during program
execution, is known as Exception.
Exception Handling: Way of handling anomalous situations in a program-run, is known as
Exception Handling.
Some common examples of Exceptions are:
 Divide by zero errors  Hard disk crash
 Accessing the elements of an array beyond its range  Opening a non-existent file
 Invalid input  Heap memory exhausted
Example:
try :
print ("result of 10/5 = ", (10/5))
print ("result of 10/0 = ", (10/0))
except :
print ("Divide by Zero Error! Denominator must not be zero!")
The output produced by above code is as shown below :
result of 10 / 5 = 2
result of 10 / 0 = Divide by Zero Error! Denominator must not be zero!
1 Marks Question:
1. Errors resulting out of violation of programming language’s grammar rules are known as:
(a) Compile time error (b) Logical error (c) Runtime error (d) Exception
2. An unexpected event that occurs during runtime and causes program disruption, is called:
(a) Compile time error (b) Logical error (c) Runtime error (d) Exception
3. Which of the following keywords are not specific to exception handling ?
(a) try (b) except (c) finally (d) else
4. Which of the following blocks is a ‘must-execute’ block ?
(a) try (b) except (c) finally (d) else
5. Which keyword is used to force an exception ?
(a) try (b) except (c) raise (d) finally
Answers:
1. (a) 2. (d) 3. (d) 4. (c) 5. (c)
Predict the output of the following code for these function calls:
(a) divide(2, 1) (b) divide(2, 0) (c) divide(“2”, “1”)
def divide(x, y):
try:
result = x/y
except ZeroDivisionError:
print ("division by zero!")
else:
print ("result is", result)
finally:
print ("executing finally clause")
Solution.
(a) divide(2, 1) result is 2
executing finally clause
(b) divide(2, 0) division by zero!
executing finally clause
(c) divide(“2”, “1”)
executing finally clause
Traceback (most recent call last):
TypeError: unsupported operand type(s) for /: 'str' and 'str'

73 | P a g e
FILE HANDLING – TEXT FILES
I. INTRODUCTION:
• Files are named locations on disk to store related information. They are used to
permanently store data in a non-volatile memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses its data when
the computer is turned off), we use files for future use of the data by
permanently storing them.
• When we want to read from or write to a file, we need to open it first. When
we are done, it needs to be closed so that the resources that are tied with the file
are freed.
• Hence, in Python, a file operation takes place in the following order:
– Open a file
– Read or write (perform operation)
– Close the file
II Types of File in Python
There are two types of files in Python and each of them are explained below in detail
with examples for your easy understanding. They are:
1) Binary file 2) Text file
II. Text files in Python
• A text file is usually considered as sequence of lines. Line is a sequence of
characters (ASCII), stored on permanent storage media. Although default
character coding in python is ASCII but supports Unicode as well.
• In text file, each line is terminated by a special character, known as End of Line
(EOL). From strings we know that \n is newline character.
• At the lowest level, text file is collection of bytes. Text files are stored in human
readable form. They can also be created using any text editor.
• Text files don’t have any specific encoding and it can be opened in normal text
editor itself.
Example of Text Files:
• Web standards: html, XML, CSS, • Tabular data: csv, tsv etc.
JSON • Configuration: ini, cfg, reg etc
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
III. OPENING OR CREATING A NEW FILE IN PYTHON
• The method open() is used to open an existing file or creating a new file. If the
complete directory is not given then the file will be created in the directory in
which the python file is stored. The syntax for using open() method is given
below.
– Syntax:
– file_object = open( file_name, “Access Mode”, Buffering )
• The open method returns file object which can be stored in the name file object
(file-handle).
File name is a unique name in a directory. The open() function will create the file with
the specified name if it is not already exists otherwise it will open the already existing
file.
File Access Modes:
• The access mode: it is the string which tells in what mode the file should be
opened for operations. There are three different access modes are available in
python.
• Reading: Reading mode is crated only for reading the file. The pointer will be
at the beginning of the file.
• Writing: Writing mode is used for overwriting the information on existing file.

74 | P a g e
• Append: Append mode is same as the writing mode. Instead of over writing
the information this mode append the information at the end.
• Below is the list of representation of various access modes in python.
Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data from the file.
• ‘w' – Write Mode: This mode is used when you want to write data into the file
or modify it. Remember write mode overwrites the data present in the file.
• ‘a' – Append Mode: Append mode is used to append data to the file. Remember
data will be appended at the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we want to write or read
the data from the same file.
• ‘a+' – Append or Read Mode: This mode is used when we want to read data
from the file or append the data into the same file.
Buffering:
• Buffering is the process of storing a chunk of a file in a temporary memory
until the file loads completely. In python there are different values can be given.
If the buffering is set to 0 , then the buffering is off. The buffering will be set
to 1 when we need to buffer the file.
Examples of Opening TEXT Files in Python
# open file in current directory
• f = open("test.txt“, “r”)
# specifying full path
– f = open(r“D:\temp\data.txt“, “r”) #–raw string
• f = open(“D:\\temp\\data.txt“, “r”) #-absolute path
IV. CLOSING FILES IN PYTHON
• After processing the content in a file, the file must be saved and closed. To do this
we can use another method close() for closing the file. This is an important method
to be remembered while handling files in python.
• Syntax: file_object.close()
string = "This is a String in Python"
my_file = open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)
V. READING INFORMATION IN THE FILE
• In order to read a file in python, we must open the file in read mode.
• There are three ways in which we can read the files in python.
– read([n])
– readline([n])
– readlines() – all lines returned to a list
Here, n is the number of bytes to be read.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
Here we are opening the file test.txt in a read-only mode and are
reading only the first 5 characters of the file using the
my_file.read(5) method.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())

75 | P a g e
Output:
Hello World
Hello Python
Good Morning #Here we have not provided any argument inside
the read() function.
#Hence it will read all the content present inside
the file.
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters of the next line.
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())

Output:
Hello World
Using this function we can read the content of the file on a line by line basis.
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]

Here we are reading all the lines present inside the text file including the newline
characters.
Example 5: Reading a specific line from
a File Output:
line_number = 4 How are You
fo =
open(“C:/Documents/Python/test.txt”,
’r’) #In this example, we are trying to read
currentline = 1 only the 4th line from the ‘test.txt’ file
for line in fo: using a “for loop”.
if(currentline == line_number):
print(line)
break
currentline = currentline +1
VI. WRITE TO A PYTHON TEXT FILE
• In order to write data into a file, we must open the file in write mode.
• We need to be very careful while writing data into the file as it overwrites the
content present inside the file that we are writing, and all the previous data will be
erased.
• We have two methods for writing data into a file as shown below.
write(string) and writelines(list)
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)

76 | P a g e
The above code writes the String ‘Hello World’ into the ‘test.txt’ file.
• The first line will be ‘Hello World’ and
my_file =
as we have mentioned \n character,
theo“w
pe”n)(“C:/Documents/Python/test.txt”,
cfiulersaonr dwthilel nmworviete t‘oHtehlelonPeyxttholinn’e. of the
my_file.write(“Hello World\n”)
• Remember if we don’t mention \n
my_file.write(“Hello Python”)
character, then the data will be written
continuously in the text file like ‘Hello
WorldHelloPython’
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)

The above code writes a list of data into the ‘test.txt’ file simultaneously.
Append in a Python Text File:
To append data into a file we must open the file in
‘a+’ mode so that we will have access to both
the append as well as write modes.

Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the
end of the ‘test.txt’ file
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end
of
the ‘test.txt’ file in a new line
flush() function
• When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write
the content of buffer onto storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it will be implicitly
called by the close(), BUT if you want to flush before closing any file you can use
flush()
REMOVING WHITESPACES AFTER READING FROM TEXT FILE
• read() and readline() reads data from file and return it in the form of string and
readlines() returns data in the form of list.
• All these read function also read leading and trailing whitespaces, new line
characters. If we want to remove these characters you can use functions
– strip() : removes the given character from both ends.
– lstrip(): removes given character from left end
– rstrip(): removes given character from right end
File Pointer
• Every file maintains a file pointer which tells the current position in the file
where reading and writing operation will take.
• When we perform any read/write operation two things happens:
– The operation at the current position of file pointer
– File pointer advances by the specified number of bytes.

77 | P a g e
1- MARK QUESTIONS
1. To read three characters from a file object f, we use ……… .
(a) f.read(3) (b) f.read() (c) f.readline() (d) f.readlines()
2. The files that consists of human readable characters
(a) binary file (b) text file (c) Both (a) and (b) (d) None of these
3. Which function is used to write a list of string in a file?
(a) writeline() (b) writelines() (c) writestatement() (d) writefullline()
4. What will be the output of the following Python code?
myFile = None
for i in range (8):
with open(“data.txt”, “w”) as myFile:
if i > 5:
break
print(myFile.closed)

(a) True (b) False (c) None (d) Error


5. What will be the output of the following Python code?
myFile = open(“story.txt”, “wb”)
print(“ Name of the file: ”, myFile.name)
myFile.flush()
myFile.close()
Suppose the content of the file ‘‘story.txt’’ is
Education Hub
Learning is the key of success.
(a) Compilation error (b) Runtime error (c) No output (d) Flushes the file when closing
them
6. What is the output of following code?
myfile=open(‘story.txt’,‘r’)
s=myfile.read(10)
print(s)
s1=myfile.read(15)
print(s1)
myfile.close()

a) Education b) Education c) Education d) Education


Hub Learning Hub Hub Hub
is Learning is Learning Learning is
is

7. What is the output of following code?


f=open(‘story.txt’, ‘r’)
s=f.readline()
lcount=len(s)
print(lcount)
f.close( )
(a) 4 (b) 2 (c) 1 (d) 8

78 | P a g e
8. What is the output of following code?
f=open(‘story.txt’, ‘r’)
str=“ ”
s=0
ts=0
while str:
str=f.readline()
ts=ts+len(str)
print(ts)
f.close()
(a) 44 (b) 43 (c) 37 (d) 45
9. What is the output of following code?
def test () :
s=open (“story.txt”, “r”)
f=s.read()
z=f.split( )
count=0
for i in z:
count=count+1
print(count)

Suppose the content of file ‘‘Para.txt’’ is


Education Hub
Electronic learning
Learning is the key of success.
(a) 7 (b) 8 (c) 5 (d) 9
10. What is the output of following code?
def test() :
f=open (“Para.txt”, “r”)
lines=0
l=f.readlines( )
for i in l:
if i [0] = = ‘E’ :
lines+=1
print(lines)
(a) 2 (b) 1 (c) 3 (d) Error

ANSWER – 1-MARK QUESTIONS

1. (a) ) 2. (b) 3. (a) 4. (a)5. (d) 6. (b) 7. (b) 8. (a)9. (b) 10.

2 MARK QUESTIONS

Q1. Write a single loop to display all the contents of a text file file1.txt after removing leading
and trailing WHITESPACES
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close( )

79 | P a g e
3. Read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
If the file contains 'GOOD' before execution, what will be the content of the file after
execution of the code
Q4. Observe the following code and answer the follow
f1=open("mydata","a")
#blank1
f1.close()
(i) what type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"
Q5. A given text file data.txt contains :
Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('data.txt')
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Q6. In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v) r+
vi) ab
vii) w+b
viii)wb
ix) w+
Q7. What would be the data types of variables data in following statements?
i) Data=f.read( )
ii) Data=f.read(10)
iii) Data=f.readline()
iv)Data=f.readlines()
Q8 Suppose a file name test1.txt store alphabets in it then what is the output of the following
code
f1=open("test1.txt")
size=len(f1.read())
print(f1.read(5))
Q9. Write a short note on flush() function.

80 | P a g e
ANSWER – 2-MARK QUESTIONS
Ans1 for line in open(“file1.txt”):
print(line.strip())
Ans2 The output will be
Hello,world!
How are you?
The first line of code is opening the file in write mode,the next two line writes text t file .the
last line
opens the file and from that reference reads the file content.file() performs the same functions
as open().Thus,the file(“output.txt”)will give the references to open the file on which read() is
applied.
Ans3 The file would now contains “Bye”only because when an existing file is openend in
write mode .it
truncates the existing data in file .
Ans4 i) Text file
ii) f1.write(“abc”)
Ans5 Line1
Line3
Line 6
Line 4
Ans6 ab and a+b mode
Ans7 a) string b)string c)string d)list
Ans 8 No Output
Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer at
the
end of file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF and,
thus,print statement prints nothing.
Ans 9
 While writing, Python writes everything into a buffer and pushes it into file at a later
time.
 When flush() function is called it immediately empties the buffer and writes into the
file.
 This function is called automatically when file is closed.

81 | P a g e
3 MARK QUESTIONS

Q1. Write a python code to find the size of the file in bytes, number of lines and number
of words.
# reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size)
f.seek(0)
L=f.readlines( )
word=L.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words ’,len(word))
f.close( )
Q2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])
Q.3 Write a program to count the words “to” and “the” present in a text file
“python.txt”.
Ans.
fname = "python.txt"
num_words = 0
f= open(fname, 'r')
words = f.read().split()
for a in words:
if (a.tolower() == “to” or a.tolower() == “the” ):
num_words = num_words + 1
print("Number of words:", num_words)
f.close()
Q.4. Write a program to display all the lines in a file “python.txt” along with line/record
number.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
count=count+1
print(count,a)
fh.close()
Q. 5 Write a program to display all the lines in a file “python.txt” which have the word
“to” in it.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
if (a.tolower().count(“to”) > 0) :
print(a)
fh.close()

82 | P a g e
3- MARK QUESTIONS

1. Write a python program to create and read the city.txt file in one go and print
the contents on the output screen.
Answer:
# Creating file with open() function
f=open("city.txt","w")
f.write("My city is very clean city.")
f.close()
# Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read()
print(dt)
f.close()
2. Consider following lines for the file friends.txt and predict the output:
Friends are crazy, Friends are naughty !
Friends are honest, Friends are best !
Friends are like keygen, friends are like license key !
We are nothing without friends, Life is not possible without friends !
f = open("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string in l but not printed
in the code, then it moves the pointer to next line in the file. In next statement we have
f.readline(18) which reads next 18 characters and place the cursor at the next position i.e.
comma (,) , in next statement f.read(10) reads next 10 characters and stores in ch3 variable and
then cursor moves to the next position and at last f.readline() function print() the entire line.

3. Write a function count_lines() to count and display the total number of lines from the
file. Consider above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
lines = f.readline()
print("no. of lines:",cnt)
f.close()

4. Write a function display_oddLines() to display odd number lines from the text file.
Consider above file – friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:

83 | P a g e
cnt+=1
lines = f.readline()
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to store data in
customer.txt file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()

4 MARK QUESTIONS
Q1. This question consists of 6 sub-questions . Attempt any 5 questions.
Below is a program to delete the line having word (passed as argument). Answer the
questions that follow to execute the program successfully.
def filedel(word) :
file1 = open(“Python.txt ”,“ ”) # Statement 1
nfile = open(“algo.txt”, “w”)
while True :
line = file1. # Statement 2
if not line :
break
else :
if word in line :
# Statement 3
else :
print(line)
nfile. (line) # Statement 4
file1.close()
. close() # Statement 5
filedel(‘write’)

(i). In which mode, program should open the file to delete the line in statement 2?
(a) w (b) r (c) r+ (d) a+
(ii). Choose the correct option to fill up the blank in line marked as Statement 3.
(a) read() (b) read(n) (c) readlines() (d) readline()
(iii). Identify the missing code for blank space in line marked as Statement 4.
(a) True (b) Flag (c) pass (d) False
(iv). Choose the correct option to fill up the blank in line marked as Statement 5.
(a) read (b) write (c) writelines (d) writeline
(v). Choose the correct option to fill up the blank in line marked as Statement 6.
(a) file 1 (b) file (c) nfile (d) None

Answer – 1
(i). (b) (ii). (d) (iii) (c) (iv). (b) (v). (c)

Q2. This question consists of 6 sub-questions . Attempt any 5 questions.


Below is a program to display all the records in a file along with line/record number from file
“status.txt”. Answer the questions that follow to execute the program successfully.

84 | P a g e
f= open ( , “r”) #Line 1
count= 0
rec=“ ”
while : #Line 2
rec = f . #Line 3
if rec = = “ ”:
#Line 4
count = #Line 5
print(count, rec, end = “ ”)
#Line 6

(i). Choose the correct option to fill up the blank marked as Line 1.
(a) status (b) “status.txt” (c) status.txt (d) file.txt
(ii). Choose the correct option to fill up the blank marked as Line 2.
(a) 0 (b) 1 (c) False (d) True
(iii). Which function will be used to read the content of file marked as Line 3?
(a) readline() (b) readlines() (c) read() (d) read(n)
(iv). Choose the correct option to fill up the blank marked as Line 4.
(a) continue (b) break (c) goto (d) label
(v) Which value will be assign to variable count in Line 5?
(a) count −1 (b) count*i (c) count +1 (d) count + i
(vi). Identify the missing code in Line 6.
(a) f.close (b) myfile.close (c) file.close() (d) f.close()

Answer – 2
(i). (b) (ii). (d) (iii). (a) (iv). (b) (v). (c) (vi). (d)

85 | P a g e
File Handling (Binary File)
There are two types of files:
Text Files- A file whose contents can be viewed using a text editor is called a text file. A text
file is simply a sequence of ASCII or Unicode characters. Python programs, contents written
in text editors are some of the example of text files.e.g. .txt,.rtf,.csv etc.

Binary Files-A binary file stores the data in the same way as as stored in the memory. The
.exe files,mp3 file, image files, word documents are some of the examples of binary files.we
can’t read a binary file using a text editor.e.g. .bmp,.cdr etc.

Text File Binary File


Its Bits represent character. Its Bits represent a custom data.
Less prone to get corrupt as change reflects as Can easily get corrupted, corrupt on even single
soon as made and can be undone. bit change
Can store different types of data (audio,
Store only plain text in a file.
text,image) in a single file.
Widely used file format and can be opened in any Developed for an application and can be opened
text editor. in that application only.

Mostly .txt,.rtf are used as extensions to text files. Can have any application defined extension.
Opening and closing of binary file is same as text file opening and closing. While opening
any binary file we have to specify ‘b’ in file opening mode.

Python has a module which does this work for us and is extremely easy to use. This module
is called pickle; it provides us with the ability to serialize and deserialize objects, i.e., to
convert objects into bitstreams which can be stored into files and later be used to
reconstruct the original objects.
pickle.dump() function is used to store the object data to the file. It takes 3 arguments.First
argument is the object that we want to store. The second argument is the file object we get
by opening the desired file in write-binary (wb) mode. And the third argument is the key-
value argument.
Pickle.load() function is used to retrieve pickled data.The steps are quite simple. We have to
use pickle.load() function to do that.
A Binary file is a file that contains information in the same format in which the information
is held in memory, ie the file content that is returned to us is raw ( with no translation or
specific encoding )

● File Handling consists of following three steps :


a) Open the file.
b) Process the file ie perform read or write operation.
c) Close the file.
● The open( ) function is used to open a data file in a program through a file-object ( or
a file handle).
● A file mode specifies the type of operation(s) ( eg read / write / append ) possible in
the opened file ie it referes to how the file will be used, once it is opened.

86 | P a g e
● The close( ) function breaks the link of the file-object and the file on the disk.
● A binary file can be opened in the modes ( ‘rb’, ‘wb’, ‘ab’, ‘rb+’, ‘wb+’, ‘ab+’)
● Pickle module in Python provides us, with the ability to serialize and de-serialize
objects, ie to convert objects into bitstreams which can be stored into files and later
be used to reconstruct the original objects.
● Serialization is also known as pickling.
● De-serialization is also known as un-pickling.
● Pickle module contains dump( ) function to perform pickling ie write data into a
binary file.
● Pickle module contains load( ) function to perform unpickling ie read data from a
binary file.
● Syntax of dump( ) function to write data :
dump(data_object, file_object)
Where data_object is the object that has to be written(dumped) to the file with the
file handle named file_object
● Syntax of load( ) function to write data :
store_object= load(file_object)
The pickled Python object is read (loaded) from the file having the file handle named
file_object and is stored in a new file handle called store_object.
● Read from and Write into a binary file :
Use ‘rb’ mode in the open( ) function to read binary files.
We hve read( ) and write( ) methods that works with string parameters and will not
work directly with binary files. Conversion of data at the time of reading and writing
is required.
Dump( ) method is used to write the objects in a binary file and load( ) method is
used to read data from a binary file.
● Search operation :
There is no pre-defined function available in python for searching records. It involves
reading of the binary file and then comparing each record with our given value. ( This
is the linear search process )
● Append operation :
To add/append data to a binary file, we must open a file in ‘ab’ mode. The file will
retain the previous records and append the new records at the end of the file.
● Update operation :
In order to update a binary file, the poisition of the file pointer must be known. To
check the position of the file pointer, we use the functions tell( ) and seek( )
● tell( ) function : It returns the current position of the file pointer in the file.
Syntax of tell( ) function : variable=file_object.tell( )
● seek( ) function : It changes the position of the file pointer by placing the file pointer
at the specified position in the open file.
Syntax of seek( ) function : file_object.seek( offset)

87 | P a g e
1 Mark Questions

1. Binary files commonly have the extension : 1


a) .TXT b) .DAT c) .DOC d) .PDF
2. The method is used to read data from a binary file. 1
3. State whether True or False : 1
When we open a file in append mode the previous data is erased.
4. Which module is required to use the built-in function dump() ? 1
a) math b) flush c) pickle d) unpickle
5. The mode used for both writing and reading data from a binary file : 1
a) wb+ b) w c) wb d) a
6. State whether True or False : 1
The type of operation that can be performed on a file depends upon the mode in
which the file is opened.
7. The module pickle is used for which of the methods in file handling : 1
(a) open( ) and close( )
(b) read( ) and write( )
(c) dump( ) and load( )
(d) None of the above
8. The statement automatically closes the file after processing on the file gets 1
over.
9. The method is used to read data from a binary file. 1
10. The method used to write an object into a binary file is : 1
a) load() b) dump() c) write() d) None of these

2 Marks Questions

1. State whether True or False : 2


a) Data stored inside the file is permanent in nature.
b) A binary file can be opened in write mode using “w” mode only.
2. Write two features of Binary files . 2
3. Write a statement in Python to perform the following operations : 2
a) To open a Binary file “BOOK.DAT” in read mode
b) To open a Binary file in read and write mode
4. Observe the following code and answer the questions that follow : 2
File = open(“Mydata”,”a”)
# Blank 1
File.close()

a) What type of file( Text / Binary ) is Mydata ?


b) Fill the Blank 1 with statement to write “ABC” in the file Mydata

5. Q (i) and (ii) are ASSERTION ( A ) and REASONING ( R ) based questions. 2


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 correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.

88 | P a g e
Q (i)
Assertion ( A ) : Access mode ‘a’ adds data to the file.
Reason ( R ) : If file exists data added to end of file, if file does not exists a new
file is created.

Q(ii)
Assertion ( A ) : Access mode ‘a’ opens a file for appending.
Reason ( R ) : The file pointer is at the end of the file if the file exists.

6. Write in short : 2
i) What is the use of open( ) method ?
ii) What is the use of tell( ) method ?
7. What is the use of load( ) and dump( ) methods? 2
8. Answer in brief : 2
i) Purpose of close( ) function.
ii) Purpose of flush( ) function.
9. Explain seek( ) method. 2

3 Marks Questions

1. a) Explain the wb+ mode in binary files. 3


b) Explain the ab+ mode in binary files.
c) Explain the rb mode in binary files.

2. a) What do you mean by serialization and de-serialization ? 3


b) What are the usage of dump( ) and load( ) functions ?
c) What are the usage of close( ) and flush( ) functions ?

3. Write a program that reads a binary file “emp.dat” and displays all records of 3
employees one by one.

4. Write a program that reads a binary file “emp.dat” and display the records of all 3
those employees who are getting salary greater than 20000.

5. a) Which method is used to write list, tuple and sequence data types in a binary file ? 3
b) Which function forces Python to write the contents of buffer to file?
c) Which area is automatically associated with the file when we open it?

4 Marks Questions

1. Consider a binary file EMP.DAT containing details empno:name:salary : 4


(separator ‘:’) Write a function function Readfile( ) to display details of those
employees who are earning between 20000 and 40000 ( both values inclusive)

2. For a Binary file, explain the processes : 4

i) Search operation
ii) Append operation
iii) Update operation

89 | P a g e
iv) tell(0 function

3. Create the file phonebook.dat that stores the details in following format : 4
Name Phone
Alex 7865443
Neha 8855342
Obtain the details from the user.

4. A file phonebook.dat stores the details in following format : 4


Name Phone
Alex 7865443
Neha 8855342
Write a program to edit the phone numbers of “Anish” in file. If there is no record
for “Anish” report error.

5 Marks Questions

1. Write a function to write numbers into a binary file and read the same. 5

2. Read the following passage and answer the questions that follow : 5

Ramesh, was assigned an incomplete task search( ) function whose purpose was to
search in a pickled file student.dat The following information about student.dat is
known :

● File contains details of students in [ roll, name, marks ] format


● File contains details of 10 students ( ie from roll 1 to 10 ) ans separate list of
each student is written in the binary file using dump( )

Ramesh has been assigned the task to complete the code and print details of roll
number 1 .

def search( ) :
f=open("student.dat", ) # statement-1
: # statement-2

while True :
rec=pickle __________ # statement-3
if( ): # statement-4
print(rec)
except : pass
# statement-5

i) In which mode Ramesh should open the file in statement-1 ?


a) r b) r+ c) rb d) wb

ii) Identify the suitable code to be used at blank space in statement-2.


a) if(rec[0]==1) b) for i in range (10) c) try d) pass

90 | P a g e
iii) Identify the function (with argument) to be used at blank space in
statement-3.
a) load( ) b) load(student.dat) c) load(f) d) load(fin)

iv) What will be the suitable code for blank space in statement-4?
a) rec[0]==2 b) rec[1]==2 c) rec[2]=2 d) rec[0]==1

v) Which statement should Ramesh use at blank space in statement-5 to


close the file?
a) file.close( ) b) close(file) c) f.close( ) d) close( )

3. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


1. Write a user defined function CreateFile() to input data for a record and add to
Book.dat .
2. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in
the binary file “Book.dat
3.
4. 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%.

5 Write a function in python to search and display details, whose destination is “Cochin”
from binary file “Bus.Dat”. Assuming the binary file is containing the following elements in
the list:
1. Bus Number
2. Bus Starting Point
3. Bus Destination

6. Write a function addrec() in Python to add more new records at the bottom of a binary
file “STUDENT.dat”, assuming the binary file is containing the following structure :
[Roll Number, Student Name]

7. Write a function searchprod( pc) in python to display the record of a particular product
from a file product.dat whose code is passed as an argument. Structure of product contains
the following elements [product code , product price]

8. Write a function routechange(route number) which takes the Route number as


parameter and modify the route name(Accept it from the user) of passed route number in a
binary file “route.dat”.

9. Write a function countrec(sport name) in Python which accepts the name of sport as
parameter and count and display the coach name of a sport which is passed as argument
from the binary file “sport.dat”. Structure of record in a file is given below ——————– –
[sport name, coach name]

10. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a
function countrec() in Python that would read contents of the file “salary.DAT” and display
the details of those employee whose salary is above 20000.

91 | P a g e
11. Amit is a monitor of class XII-A and he stored the record of all the students of his class in
a file named “class.dat”. Structure of record is [roll number, name, percentage]. His
computer teacher has assigned the following duty to Amit
Write a function remcount( ) to count the number of students who need remedial class
(student who scored less than 40 percent)

Marking Scheme
1 Mark Questions

1. b) .DAT 1
2. load() 1
3. False 1
4. c) pickle 1
5. a) wb+ 1
6. True 1
7. (c) dump( ) and load( ) 1
8. with 1
9. load() 1
10. b) dump() 1
2 Marks Questions

1. a) True 2
b) False
2. i) It can handle large files. 2
ii) It consists of data with a specific pattern without any delimiter,
3. a) f1=open(“BOOK.DAT”,”r”) 2
b) f2=open(“BOOK.DAT”,”w+”)
4. a) Textfile. 2
b) File.write(“ABC”)
5. i) Option B is correct. 2
ii) Option A is correct.
6. i) It opens a file on disk and associates it with a file handle. 2
ii) It tells us the current position of the file pointer within the file.
7. load( ) function is used for reading data fromn a binary file. 2
dump( ) function is to write the object in a binary file.
8. i) It breaks the link of the file object and the file on disk. After file is closed, no file 2
operations can be don on the file.

ii) It forces the writing of data on the disk still pending in output buffers.
9. Syntax is seek( offset, from_what) 2
It changes the current file pointer position. The offset argument indicates the
number of bytes to be moved. The from_what argument specifiesthe reference
[position from where the bytes are to be moved.
3 Marks Questions

92 | P a g e
1. a) wb+ mode is used to open a binary file in write and read modes both. 3
b) ab+ mode is used to open a binary file in append and read mode both.
Previous content is preserved.
c) rb mode is used to open a binary file in read only mode. No other operation can
be performed.
2. a) Serialization is to convert objects into bitstreams which can be stored into 3
files, whereas de-serialization is used to reconstruct the original objects. It is
also known as pickling.
b) The dump( ) function is used to perform pickling ie write data into a binary file.
Whereas the load( ) function is used to perform unpickling ie read data from a
binary file.

c) close( ) function delinks the file_object with the file on the disk. The flush( )
function forces the write operation on the disk file which remains in the pending
status.
3. import pickle 3
f1=open("emp.dat","rb")
e=pickle.load(f1)
for x in e :
print(x)
f1.close( )
4. import pickle 3
f1=open("emp.dat","rb")
e=pickle.load(f1)
for x in e :
if(e[x]>20000) :
print(x)
f1.close()
5. a) writelines( ) 3
b) flush( )
c) buffer
4 Marks Questions
1. def Readfile( ) : 4
i=open(“EMP.DAT”,”rb+”)
x=i.readline()
while(x) :
I=x.slpit(‘:’)
If ((float(I[2])>=20000) and ( float(I[2])<40000)) :
print(x)
x=i.readline()
i.close()
2. 4
i) Search operation :
There is no pre-defined function available in python for searching records. It
involves reading of the binary file and then comparing each record with our
given value. ( This is the linear search process )

ii) Append operation :

93 | P a g e
To add/append data to a binary file, we must open a file in ‘ab’ mode. The
file will retain the previous records and append the new records at the end of
the file.

iii) Update operation :


In order to update a binary file, the poisition of the file pointer must be
known. To check the position of the file pointer, we use the functions tell( )
and seek( )

iv) tell( ) function : It returns the current position of the file pointer in the
file.

Syntax of tell( ) function : variable=file_object.tell( )


3. fp1==open("phonebook.dat","w") 4
fp1.write("Name")
fp1.write(" ")
fp1.write("Phone")
fp1.write("\n")
while True :
name=input("Enter name : ")
phno=input("Enter phone no : ")
fp1.write(name)
fp1.write(" ")
fp1.write(phno)
fp1.write("\n")
ch=input("Want to enter more = y / n :")
if ch=='N' or ch=='n' :
break
fp1.close( )
4. fp==open("phonebook.dat","w+") 4
list=" "
while list :
pos=fp.tell( )
list=fp.readline( )
name,phone=list.split( )
if name= = "Anish" :
phone=input("Enter new number : ")
fp.seek(pos,0)
fp.write(name)
fp.write(" ")
fp.write(phone)
fp.close( )
break
5 Marks Questions
1. def binfile( ) : 5
import pickle
file=open("mydata.dat","wb")
while True :
x=int(raw_input("Enter number : " ))
pickle.dump(x.file)

94 | P a g e
ans=raw_input(More data y / n : ")
if ans.upper( ) =='N ' :
break
file.close( )
2. i) Correct option is c) rb 5
ii) Correct option is c) try
iii) Correct option is c) load(f)
iv) Correct option is d) rec[0]==1
v) Correct option is c) f.close( )
3 import pickle 5
def createfile():
fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()

createfile() # This function is called just to verify result and not required in exam

def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
fobj.close()
return num

n=countrec("amit") # This function is called just to verify result and not required in
exam
print("Total records", n) # This statement is just to verify result and not required in
exam

4 import pickle 5
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:

95 | P a g e
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
5 import pickle 5
def countrec():
fobj=open("bus.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() # This function is called just to verify result
print(n)
6 import pickle 3
def addrec():
fobj=open("student.dat","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
pickle.dump(rec,fobj)
fobj.close()
addrec()
7 import pickle 5
def searchprod(pc):
fobj=open("product.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[0]==pc:
print(rec)
except:
fobj.close()

n=searchprod(1) # This function is called to verify the result


8 import pickle 5
def routechange(rno):
fobj=open("route.dat","rb")
try:
while True:
rec=pickle.load(fobj)
if rec[0]==rno:
rn=input("Enter route name to be changed ")

96 | P a g e
rec[1]=rn
print(rec) #This statement is called to verify the change in the record
except:
fobj.close()

routechange(1) # This function is called to verify the result


9 def countrec(sn): 5
num=0
fobj=open("data.dat","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=pickle.load(fobj)
if rec[0]==sn:

print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:
fobj.close()
10 def countrec(): 5
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result
11 def countrec(): 5
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

97 | P a g e
File Handling (CSV File)
CSV (Comma Separated Values) is a file format for data storage which looks like a text
file. The information is organized with one record on each line and each field is separated by
comma.

CSV File Characteristics


 One line for each record
 Comma separated fields
 Space-characters adjacent to commas are ignored
 Fields with in-built commas are separated by double quote characters.
When Use CSV?
 When data has a strict tabular structure
 To transfer large database between programs
 To import and export data to office applications, Qedoc modules
 To store, manage and modify shopping cart catalogue
CSV Advantages
 CSV is faster to handle.
 CSV is smaller in size
 CSV is easy to generate
 CSV is human readable and easy to edit manually
 CSV is simple to implement and parse
 CSV is processed by almost all existing applications
CSV Disadvantages
 No standard way to represent binary data
 There is no distinction between text and numeric value.
 Poor support of special characters and control characters.
 CSV allows to move most basic data only. Complex configurations cannot be
imported and exported this way
 Problem.s with importing CSV into SQL (no distinction between NULL and quotes)
Write / Read CSV FILE
Writing and reading operation from text file is very easy. First of all we have to import csv
module for file operation/method call.
Writing: we open file in ‘w’ writing mode using open() method which create newFile like
object. Through csv.writer() method ,we create writer object to call writerow() method to
write objects.
Reading: we open the file in ‘r’ mode and create newFile like object,further we create
newfilereader object using csv.reader()method to read each row of the file.

CSV File
 CSV (Comma-separated values) is a common data exchange format used by the
applications to produce and consume data.
 A CSV file is a simple text file where each line contains a list of values (or fields)
delimited by commas (mostly), but you will encounter CSV files where data is
delimited using tab (\t) or pipe (|) or any other character.
 The first line of the CSV file represents the header containing a list of column names
in the file.
 CSV file is commonly used to represent tabular data
See the following table

98 | P a g e
Name Class Section
Amit X A
Sumit XI B
Ashish XII C

The above table will be stored in CSV format as follows:

If the values in the table contain comma(,) like below in column Address
Name Class Address
Amit X Fr. Agnel School, Delhi
Sumit XI Fr. Agnel School, Delhi
Then in CSV it will be stored like below (Values containing comma will be enclosed in
double quotes)

Python Provides CSV module to work with csv file:


Main Functions are:
1. reader()
2. writer()
3. DictReader()
4. DictWriter()

1. reader() function : This function help us to read the csv file. This function takes a
file object and returns a _csv.reader object that can be used to iterate over the contents
of a CSV file.
How to read entire data from data.csv file?
Let we try to read the following file ie “data.csv”
data.csv
CODING OUTPUT
import csv [‘Name’ , ‘Class’ , ‘Subject’]
f = open(“data.csv”, ‘r’) [‘Amit’ , ‘XII’ , ‘ CS’]
row = csv.reader(f) [‘Sumit’ , ‘X’ , ‘IP’]
for i in row : Notice that each line in the CSV file is returned as a list of
print(i) strings
f.close()

Line-wise explanation of the code


1. The first line is importing a csv module.
2. This line is opening a file (data.csv) in reading mode and f is file object or file
handle.
3. This line is returning a csv.reader object that can be used to iterate over csv file
contents
4. We are using loop on the object which is returned by the previous line.

99 | P a g e
CODING OUTPUT
import csv
f = open(“data.csv”, ‘r’) Returns the memory address where csv.reader object is
row = csv.reader(f) stored
print(row)
f.close()

How to read specific column from data.csv?


CODING OUTPUT Actual Data of File
import csv Name Subject [‘Name’ , ‘Class’ , ‘Subject’]
f = open(“data.csv”, ‘r’) Amit CS [‘Amit’ , ‘XII’ , ‘ CS’]
row = csv.reader(f) Sumit IP [‘Sumit’ , ‘X’ , ‘IP’]
for i in row :
print(i[0] , i[2])
f.close()
#The above code is reading first and
third column from “data.csv” file

If you want to skip the First Row (header of the table)


CODING OUTPUT Actual Data of File
import csv [ ‘Amit’ , ‘CS’] [‘Name’ , ‘Class’ , ‘Subject’]
f = open(“data.csv”, ‘r’) [‘Sumit’ , ‘IP’ ] [‘Amit’ , ‘XII’ , ‘ CS’]
row = csv.reader(f) [‘Sumit’ , ‘X’ , ‘IP’]
next(row)
for i in row :
print(i[0] , i[2])
f.close()

next () function will jump to the next


row.

import csv
f = open(“data.csv”, ‘r’) [‘Sumit’ , ‘IP’ ] [‘Name’ , ‘Class’ , ‘Subject’]
row = csv.reader(f) [‘Amit’ , ‘XII’ , ‘CS’]
next(row) [‘Sumit’ , ‘X’ , ‘IP’]
next(row)
for i in row :
print(i[0] , i[2])
f.close()
If we use the next() function two times
then it will skip two lines from
beginning

If there is any other delimiter other than comma like in the following file

100 | P a g e
CODING OUTPUT
import csv [‘id’ , ‘name’ , ’email’ , ‘salary’]
f = open(“data.csv”, ‘r’) [‘1’ , ‘Amit’ , ‘amit@mail.com’ , ‘25000’]
row = csv.reader(f, delimiter = ‘l’) [‘2’ , ‘Sumit’ , ‘sumit@mail.com’ , ‘30000’]
for i in row : [‘3’ , ‘Ashu’ , ‘ashu@mail.com’ , ‘40000’]
print(i)
f.close()

2. writer() function : This function help us to write data in a csv file. It accepts the
same argument as the reader() function but returns a writer object (i.e _csv.writer)
There are two main methods used in writing in csv file
1. writerow()
2. writerows()

using writerow():
CODING DATA.CSV
import csv Name , Class
f = open(“data.csv”, ‘w’) ‘Amit’ , ‘XII’
wr = csv.writer(f)
wr.writerow([‘Name’ , ‘Class’])
wr.writerow([‘Amit’ , ‘XII’])
f.close( )

using writerows():
CODING DATA.CSV
import csv Name, Class, Subject
fields = [‘Name’ , ‘Class’ , ‘Subject’] Amit, XII, CS
rows = [[“Amit” , ‘XII’ , ‘CS’] , Sumit, X, IP
[‘Sumit’ , ‘X’ , ‘IP’] , Ashu, XI, CS
[‘Ashu’ , ‘XI’ , ‘CS’]]
f = open(“data.csv” , ‘w’ , newline = ‘ ‘)
wr = csv.writer(f)
wr.writerow(fields)
wr.writerows(rows)
f.close()

Reading a CSV file with DictReader:


This function(DictReader) is working similar to reader(). This function return lines as a
dictionary instead of list.
CODING OUTPUT data.csv
import csv {‘Name’ : ‘Amit, ‘Class’ : ‘XII’} Name, Class
f = open(“data.csv” , ‘r’) {‘Name’ : ‘Sumit, ‘Class’ : ‘X’} Amit, XII
row = csv.DictReader(f) {‘Name’ : ‘Ashu, ‘Class’ : ‘XI’ Sumit, X
for i in row: Ashu, XI
print(i)

This CSV file has no header. So we have to provide field names via
the fieldnames parameter
CODING

101 | P a g e
import csv Amit, XII, CS Syntex:
wr_obj.writerows(field_name)
f = open(“data.csv” , ‘r’) Sumit, X, IP
row = csv.DictReader(f, fieldnames = [‘Name’
Ashu, XI,, ‘Class’
CS , ‘Subject’])
for i in row:
print(i)
f.close()
writer() Function of CSV File:
OUTPUT 1. writerow()- print
{‘Name’ : ‘Amit, ‘Class’ : ‘XII’ , ‘Subject’ ‘CS’}
record:line by line Function of CSV File:
{‘Name’ : ‘Sumit, ‘Class’ : ‘X’ , ‘Subject’ : ‘IP’}
Syntex: 1. reader()
2. writer()
{‘Name’ : ‘Ashu, ‘Class’ : ‘XI’ , ‘Subject’ : ‘CS’}
wr_obj.writerow(row_name
3. DictReader()
)
data.csv 4. DictWriter()method
2. writerows()- print all
record at a time.

reader(): writer() method ,we create writer


object to call writerow() method to write
objects.
Syntax:
Reading a CSV file with DictReader: reader_obj= csv.reader(file_object)
This function(DictReader) is working similar to
reader(). This function return lines as a dictionary writer():reader()method to
instead of list. read each row of the file.
Syntex: Syntex:
DictReader_Object = csv.DictReader(file_obj) writer_obj= csv.writer(file_object)

102 | P a g e
1 Marks
Q1. Which of the following module is provided by Python to do several operations on the
CSV files?
(A) os (B) xls (C) csv (D) py
Q2. Which of the following is tasks cannot be done or difficult with CSV module?
(A) Storing data in tabular form (B) Finding data uniquely
(C) Saving data permanently (D) All of these
Q3. The writer() function of csv module has how many mandatory parameters?
(A) 4 (B) 3 (C) 2 (D) 1
Q4. Which of these is not relevant to csv file?
(A) Text file (B) Binary file
(C) Easily openable in text editor (D) None of the above
Q5. You are having myfile.csv file on c drive. You want to access it in python, how can you
do this?
(A) source=”c:\\myfile.csv” data = pd.read_csv(source)
(B) source=”c:\\myfile.csv” data = pd.reads_csv(source)
(C) source=”c:\\myfile.csv” data = pd.reader(source)
(D) None of the above
2 Marks
Q4.
Assertion: To specify a different delimiter while writing into a csv file, delimiter argument
is used with
csv.writer().
Reason: The CSV file can only take a comma as a delimiter.
(A) Both Assertion and reason are true and reason is the correct explanation of assertion.
(B) Assertion and reason both are true but reason is not the correct explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true.
Q7.
Assertion: Every record in a CSV file is stored in reader object in the form of a list.
Reason: writerow() method allows us to write a list of fields to the CSV file.
(A) Both Assertion and reason are true and reason is correct explanation of assertion.
(B) Assertion and reason both are true but reason is not the correct explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true.
Q10.
Assertion: The CSV module in Python’s standard library presents methods to perform
read/write operations on CSV files.
Reasoning: To write data to a CSV file, we can use built-in function writer().
(A) Both Assertion and reason are true and reason is the correct explanation of assertion.
(B) Assertion and reason both are true but reason is not the correct explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true
Q11.
Assertion: To open a CSV file employee.csv in write mode, we can give python statement
as follows:
fh=open('employee.csv’)
Reasoning: If we try to write on a csv file that does not exist, the file gets Created
(A) Both Assertion and reason are true and reason is the correct explanation of assertion.
(B) Assertion and reason both are true but reason is not the correct explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true.

103 | P a g e
5 Marks
Q1 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he has
. been assigned an incomplete python code (shown below) to create a CSV File 'Student.csv' (content
shown below). Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
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("Enter 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.
a) csv file b) CSV c) csv d) Csv
ii. Identify the missing code for blank space in line marked as Statement-2?
a) "School.csv","w" b) "Student.csv","w"
c) "Student.csv","r" d) "School.csv","r"
iii. Choose the function name (with argument) that should be used in the blank
space of line marked as Statement-3
a) reader(fh) b) reader(MyFile) c) writer(fh) d) writer(MyFile)
iv. Identify the suitable code for blank space in line marked as Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION' b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section' d) roll_no,name,Class,sectionc) co.connect()
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?
a) dump() b) load() c) writerows() d) writerow()

Marking Scheme
1 Marks
Q1. (C) csv
Q2. (B) Finding data uniquly
Q3. (D) 1
Q4. (B) Binary file
Q5. (A) source=”c:\\myfile.csv” data = pd.read_csv(source)
2 Marks
Q4. (C) Assertion is true, reason is false.
Q7. (B) Assertion and reason both are true but reason is not the correct explanation of
assertion.

104 | P a g e
Q10. (C) Assertion is true, reason is false.
Q11. (D) Assertion is false, reason is true.
5 Marks
Q1
i. Correct Answer : c) csv
ii. Correct Answer : b) "Student.csv","w"
iii. Correct Answer: c) writer(fh)
iv. Correct Answer : d) roll_no,name,Class,section
v. Correct Answer : c) writerows()

STACK Data Structure


Syllabus :
Data Structure: Stack, operations on stack (push & pop), implementation of stack using LIST
Data Structure is the method of organising data in the memory of the computer for efficient
processing of Data.
Types of Data Structures :
1. List 2. Stack 3. Queue
We already have studied Lists in class 11 and its review in class 12. The topic STACK is in the
syllabus of class 12 . ( Queue is not in syllabus)
Stack: A stack is an arrangement of a set of homogeneous elements one upon another and is
based on the principle of Last – In – First – Out (LIFO).
It has two major operations PUSH & POP .
PUSH : This operation adds an element at the top of the stack. Then the added element becomes
the top of the Stack.
If the STACK is already full and no element can be pushed into the STACK ,
it is known as OVERFLOW.
POP : This operation removes an element from the top of the stack.
Then the previous element from the deleted position becomes the top of the Stack.
If the STACK is empty it is known as UNDERFLOW.
Implementation of Stack in Python: We can implement Stack in python using List. Let us
write a program in python to create a stack of integer and perform some Push and Pop operation
according to the user choice.
#Program: To implement Stack Using List.
def PUSH(stk,ele): #Function to push element in stack.
stk.append(ele)
def POP(stk): #Function to pop element from stack.
if len(stk) == 0:
print("Stack is empty!")
else:
ele = stk.pop()
def DISPLAY(stk): #Function to display elements of stack.
L = len(stk)
if L == 0:
print("Stack is empty!")

105 | P a g e
else:
print("The elements in the stacks are:")
for i in range(L-1, -1, -1):
print(stk[i])
# main
stk = [] #Creating an empty List for Stack
while True:
print ("PRESS 1 for Push \n PRESS 2 for Pop")
print ("PRESS 3 for Display \n PRESS 4 for Exit")
ch = int(input())
if ch == 1:
item = int(input("Enter data: "))
PUSH(stk, item)
elif ch == 2:
POP(stk)
elif ch == 3:
DISPLAY(stk)
elif ch == 4:
break
else:
print ("Invalid Choice...")
Mind Map:
STACK

POP:
 UNDERFLOW
PUSH:
 POP(Stk):
 OVERFLOW
o if len(Stk) == 0:
 PUSH(Stk,ele):  print(“Underflow”)
o Stk.append(ele) o else:
 Stk.pop()

APPLICATIONS OF STACK :
1. Reverse a word / line : In a Stack, the elements can be read from TOP end, ie the last
element. Hence it is used to reverse a word or line.
2. The Compiler uses Stack to store the previous state of a program, when a function is
called(activated) . ( During Recursion / Recursive funcrion calls)
3. Undo Mechanism in Text Editors.
First of all , let us solve some basic questions :
A) Fill in the blanks : ( These are 1 marks questions )
i) means organization of data. (Ans: Data structure)
ii) Stack is also known as ...............list. (Ans: LIFO)
iii) Insertion of an element in a Stack is known as.......... (Ans: push )
iv) Deletion of an element from top of Stack is known as ....... (Ans: pop)

106 | P a g e
v) LIFO stands for ........... (Ans: Last-In-First-Out)
B) State whether the statements are True or False : ( These are 1 marks questions )
i) Insertion and Deletion from a Stack, takes place only from TOP. (Ans: True)
ii) If a Stack is Empty, it is termed as STACK OVERFLOW. (Ans: False)
iii) Removal of an element from top of stack is termed as POP. (Ans:True)
iv) Undo mechanism of text editors is an application of Stack. (Ans: True)
v) Insertion of an element to the top of stack is termed as PUSH. (Ans: True)

Questions:
S.No. Question
Q 01 Stack is also known as: 1
a) First-in First-out b) Last-in-First-out c) Both a and b d) None of these
Ans b) Last-in-First-out
Q 02 In a stack, if a user tries to remove an element from empty stack, it is known as: 1
a) Underflow b) Empty c) Overflow d) None
Ans a) Underflow
Q 03 What type of data structure a stack is? 1
a) Linear b) Non-Linear c) Both A and B d) None
Ans a) Linear
Q 04 Which one of the following is an application of Stack Data Structure? 1
a) Managing Function Call b) Arithmetic Expression Evaluation
c) Undo Redo d) All of the above
Ans d) All of the above
Q 05 Which data structure we can use for reversing a string? 1
a) Queue b) List c) Stack d) Dictionary
Ans c) Stack
Q 06 Stack can be implemented in Python using: 1
a) Tuple b) Dictionary c) Set d) List
Ans d) List
Q 07 What are the two operations of stack? 1
Ans The two operations of stack are Push and Pop
Q 08 How do we test for empty stack? 1
Ans if len(stk) == 0:
print(“Stack is Empty.”)
Q 09 Why do we use append() method of list in push operation? 1
Ans To push data at the top of the stack.
Q 10 ASSERTION AND REASONING based questions. Mark the correct choice as 1
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
Assertion (A): - In stack during pop operation it is necessary to check for
underflow.
Reasoning (R): - Underflow is the when the memory allocated to the stack gets
full.
Ans c) A is True but R is False
Q 11 Define any two characteristics of stacks. 2

107 | P a g e
Ans Stack is a data structure in which insertion and deletion is done from one end
only, usually referred to as TOP.
Stack follows LIFO principle using which an element inserted in the last will be
the first one to be out.
Q 12 Define any two application of stacks. 2
Ans Reversing a string.
In text/image editor for redo/undo the editing.
Q 13 Write down the status of Stack after each operation: 2
Stack = [10,20,30,40] where TOP item is 40
Push 70
Push 100
Pop an item from Stack
Ans |100|
| 70 | | 70 | | 70 |
| 40 | | 40 | | 40 |
| 30 | | 30 | | 30 |
| 20 | | 20 | | 20 |
| 10 |, | 10 | and | 10 |
Q 14 What will be the output of the following code: 2
def PUSH(L):
Stk = []
for i in L:
if i % 5 == 0:
Stk.append(i)
for i in range(len(L)-1, -1, -1):
print(L[i])
else:
print(“Stack is Empty”)
PUSH([12,23,34,54,56,67,87,89])
Ans Stack is Empty
Q 15 What will be the output of the following code: 2
def POP(Stk):
if len(Stk) == 0
print(“Stack is Empty”)
else:
while len(Stk) != 0:
x = Stk.pop()
if x[0] not in “AEIOUaeiou”:
print(x)
Stk = [“Hello”, “How are you”, “I am fine”, “Thank you”]
POP(Stk)
Ans Thank you
How are you
Hello
Q 16 What will be the output of the following code: 2
def G75(D):
Stk = []
for k in D:
if D[k] > 75:
Stk.append(k)

108 | P a g e
if len(Stk) == 0:
print(“Stack is Empty”)
else:
while len(Stk) != 0:
print(Stk.pop())
D = {“Ajay”:76, “Vijay”:99, “Sanjay”: 75}
G75(D)
Ans Vijay
Ajay
Q 17 Find the error in the following code and write the correct code and underline the 2
corrected ones:
Def POP(Stk):
If len(Stk) == 0
print(“Stack is Empty”)
else
F=1
while len(Stk) != 0:
F = F * Stk.pop()
return F
Ans def POP(Stk):
if len(Stk) == 0
print(“Stack is Empty”)
else:
F=1
while len(Stk) != 0:
F = F * Stk.pop()
return F
Q 18 Find the error in the following code and write the correct code and underline the 2
corrected ones:
def PUSH(Stk, L):
for w IN L:
if w[0] IN “AEIOUaeiou”:
Stk.extend(w)
Ans def PUSH(Stk, L):
for w in L:
if w[0] in “AEIOUaeiou”:
Stk.append(w)
Q 19 Find the error in the following code and write the correct code and underline the 2
corrected ones:
def Display(L)
l = len L
if l == 0:
print(Stack is Empty!!!)
else:
print("Elements in stack are:")
For i in range(l - 1, -1, -1):
print(L[i])
Ans def Display(L):
l = len(L)

109 | P a g e
if l == 0:
print("Stack is Empty!!!")
else:
print("Elements in stack are:")
for i in range(l - 1, -1, -1):
print(L[i])
Q 20 Write a function in Python PUSHD3(L), where L is a list of numbers. from this 3
list push all numbers divisible by 3 into a stack implemented using a list. Display
the stack if it has at least one element, otherwise display appropriate error
message.
Ans def PUSHD3(L):
Div3 = []
for i in L:
if i % 3 == 0:
Div3.append(i)
if len(Div3) == 0
print(“Stack is Empty”)
else:
while len(Div3) != 0:
print(Div3.pop())
Q 21 Sakshi has created a dictionary D, containing names and salary as key value pairs 3
of 5 employees. Write two separate functions to perform the following
operations:
● PUSH(HS, D), where HS is the stack and D is the dictionary which containing
names and salaries. Push the keys (name of the employee) of the dictionary into
a stack, where the corresponding value (salary) is greater than ₹75,000.
● POP(HS), where HS is the stack. Pop and display the content of the stack.
Ans def PUSH(HS, D):
for k in D:
if D[k] > 75000:
HS.append(k)
def POP(HS):
if len(HS) == 0
print(“Stack is Empty”)
else:
while len(HS) != 0:
x = HS.pop()
print(x)
Q 22 Write the functions in python, PUSH(Stk, L) and POP(Stk), where Stk is the 3
stack and L is a list of strings. In PUSH function read the list and push those
string into the stack which start with a vowel. And in POP function display the
stack.
Ans def PUSH(Stk, L):
for w in L:
if w[0] in “AEIOUaeiou”:
Stk.append(w)
def POP(Stk):
if len(Stk) == 0
print(“Stack is Empty”)
else:

110 | P a g e
while len(Stk) != 0:
x = Stk.pop()
print(x)
Q 23 What will be the output of following code: 3
def PUSH(Stk, N)
for i in range(N,0,-1):
Stk.append(i)
def POP(Stk):
if len(Stk) == 0
print(“Stack is Empty”)
else:
F=1
while len(Stk) != 0:
F = F * Stk.pop()
return F
Stk = []
PUSH(Stk, 5)
print(POP(Stk))
Ans 120
Q 24 Write a function DoubleStack(Stk), where Stk is a stack containing integers. In 3
the function pop all the element of the stack and double the elements then push
back to the stack in its original place.
For example:
Stk = [10,20,30,40,50]
After the execution of the function the stack should be:
Stk = [20,40,60,80,100]
Ans Def DoubleStack(Stk):
tempStk = []
while len(Stk) != 0:
x = Stk.pop()
tempStk.append(x*2)
while len(tempStk) != 0:
x = tempStk.pop()
Stk.append(x)
Q 25 Write the functions in python, PUSH(L, data), POP(L), DISPLAY(L) to add a 4
new integer, delete an integer from a List of numbers L and display the element
of the stack, considering them to act as push and pop operations of the Stack data
structure.
Ans def PUSH(L, data):
L.append(data)
def POP(L):
if len(L) == 0:
print("Stack is empty!")
else:
return L.pop()
def Display(L):
l = len(L)
if l == 0:
print("Stack is Empty!!!")

111 | P a g e
else:
print("Elements in stack are:")
for i in range(l - 1, -1, -1):
print(L[i])
Q 26 Write a program to reverse a string using stack. 4
Ans def revStr(S):
stk = []
rS = ‘’
for i in S:
stk.append(i)
while len(S) != 0:
rS = rS + S.pop()
return rS
S = input(“Enter a String:”)
rS = revStr(S)
print(“Reverse String is:”, rS)
Q 27 Write a function PUSH(L) and POP(Stk), where L is List of integers and Stk is 4
a stack. In PUSH function create two stack StkO and StkE, then read the list L
and push all the even element in StkE and push all the odd element in StkO. At
last return both the stacks. In POP function pop the number from the stack and
display.
Ans def PUSH(L):
StkO = []
StkE = []
for i in L:
if i%2 == 0:
StkE.append(i)
else:
StkO.append(i)
return StkO, StkE
def POP(Stk):
if len(Stk) == 0
print(“Stack is Empty”)
else:
while len(Stk) != 0:
print(Stk.pop())
Q 28 def PUSH(Stack,N): 5
Stack. ( N) #Statement 1
def POP(Stack):
if : #Statement 2
return "Underflow"
else:
return Stack. #Statement 3
Stack=[]
Books=[‘Python’, ‘C’, ‘Java’, ‘C++’, 'PHP', ‘C#]
for i in range(0,len(Books), ): #Statement 4
PUSH(Stack,Books[i])
while len(Stack) != 0:
print( ) #Statement 5

112 | P a g e
Required Output:
C
C++
C#
Fill the above statement based on given questions:
i Identify the suitable code for the blank of statement 1.
a) .append b) .insert c) .extend d) .add
Ans a) append
ii Fill the statement 2, to check the stack is empty.
a) Stack = [] b) Stack.isEmpty()
c) len(Stack) == 0 d) No of the above
Ans c) len(Stak) == 0
iii Fill the statement 3, to delete an element from the stack.
a) pop(1) b) pop() c) del Stack[1] d) delete(1)
Ans b) pop()
iv Fill the statement 4, to insert the alternate element from Books list.
a) 3 b) 0 c) -1 d) 2
Ans d) 2
v Fill the statement 5, to call the pop function.
a) pop(Books) b) pop(Stack)
c) call pop(Stack) d) def pop(Stack)
Ans b) pop(Stack)
Q 29 PUSH(S,N): #Statement 1 5
S.append(N)
def POP(S):
if S != []:
S.pop() #Statement 2
else:
return None
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
ST=[]
for k in R:
if R[k] >= 75:
PUSH( ) #Statement 3
True: #Statement 4
if ST != []:
print(POP(ST))
else:
#Statement 5
Required Output:
TOM
ANU
BOB
OM
Fill the above statement based on given questions:
i Fill the Statement 1, to define a function.
a) DEF b) Def c) def d) define
Ans c) def
ii Fill the Statement 2, to return the popped data.

113 | P a g e
a) send b) pass c) assign d) return
Ans d) return
iii Fill the Statement 3, to pass the proper arguments.
a) ST, k b) k, ST c) ST d) k
Ans a) ST, k
iv Fill the Statement 4, to complete the looping structure.
a) for b) do while c) if d) while
Ans d) while
v Fill the Statement 5, to stop the infinite loop.
a) stop b) Stop c) break d) Exit
Ans c) break
Q 30 status = _____________________________ #Statement 1 5
def PUSH(cust):
if cust[2] == "Goa":
L = [cust[0],cust[1]]
.append(L) #Statement 2
def POP():
if (status) == 0: #Statement 3
print( ) #Statement 4
while != 0: #Statement 5
x = status.pop()
print(x)
PUSH([“Gurdas”, “99999999999”,”Goa”])
PUSH([“Julee”, “8888888888”,”Mumbai”])
PUSH([“Murugan”,”77777777777”,”Cochin”])
PUSH([“Ashmit”, “1010101010”,”Goa”])
POP()
Required Output: [“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Fill the above statement based on given questions:
i Fill the Statement 1, to create a empty stack using list.
a) () b) {} c) [] d) “”
Ans c) []
ii Fill the Statement 2, to complete push operation.
a) cust b) status c) cust[top] d) status[top]
Ans b) status
iii Fill the Statement 3, to find the size of stack.
a) size b) length c) count d) len
Ans d) len
iv Fill the Statement 4, to display proper message where underflow occurs.
a) “Stack is Empty” b) Stack is Empty
c) [Stack is Empty] d) {Stack is Empty
Ans a) “Stack is Empty
v Fill the Statement 5, to iterate the loop properly.
a) size(status) b) len(status) c) count(status) d) length(status)
Ans len(status)

THANKS

114 | P a g e
Roll No:

JAWAHAR NAVODAYA VIDYALAYA, SHILLONG REGION


SUB: COMPUTER SCIENCE (083) CLASS: XII
PRACTICE PAPER
MAX MARKS:70 TIME: 3 HOURS

GENERAL INSTRUCTIONS:
 The question paper consists of 35 questions divided in 5 sections
 Section – A consists of 18 questions (1 to 18), each carrying 1 mark.
 Section – B consists of 6 questions (19 to 25), each carrying 2 marks.
 Section – C consists of 5 questions (26 to 30), each carrying 3 marks.
 Section – D consists of 2 questions (31 to 32), each carrying 4 marks.
 Section – E consists of 3 questions (33 to 35), each carrying 5 marks.
 All programming questions are to be answered using Python Language only.

Section - A
1. Which of the following is an invalid identifier in Python? 1
A) Break
B) 2024xyz
C) Num
D) firstname
2. Which of the following in not a logical operator in Python? 1
A) not
B) or
C) in
D) and
3. Which of the following is an immutable data types in Python? 1
A) List
B) Stack
C) String
D) Dictionary
4. What will be the output of the following code? 1
print(10**3*5**2-1)
A) 299
B) 24999
C) 2499
D) 2249
5. S=’Incredible India 2024’ 1
Which of the following statements is having error?
A) print(S)
B) print(S+” ”)
C) S[0]=’i’
D) print(S*3)
6. Which of the following mode in the file opening statement generates error 1
if the file does not exists?
A) a+
B) r+
C) w+
D) wb+

115 | P a g e
7. A tuple in RDBMS is referred to ___________ of a table. 1
A) Record
B) Field
C) Table
D) Key
8. Mbps stands for 1
A) Millions bits per second
B) Mega Byte per second
C) More bits per second
D) Mega Bits per second
9. Choose the correct statement, considering the following statement. 1
D1.update(D2) # D1 and D2 are dictionaries
A) It will merge all the elements of D1 in D2
B) It will merge all the elements of D2 in D1
C) It will create a new dictionary
D) None of the above
10. Mr. Das is creating a field that contains alphanumeric values with fixed 1
length. What SQL data type should be used by Mr. Das?
A) Numeric
B) Varchar
C) Char
D) Integer
11. ____________ is a service that does the mapping between domain name 1
and IP address.
A) DNS
B) HTTP
C) TCP
D) IP
12. Select the correct output of the following 1
s=”Python Program is very Interesting. I have stated in 2023.”
L=s.split(“ ”)
for i in L:
if len(i)==4:
print(i,end=” “)
A) very have 2023
B) very have
C) Pyth very 2023
D) Error
13. Which of the following sends data to the specific computers? 1
A) Hub
B) Router
C) Bridge
D) Switch
14. Which of the following command is used to change some values in existing 1
row?
A) Update
B) Insert
C) Alter
D) Order By
15. Predict the output of the following. 1
x=9

116 | P a g e
while x>0:
print(x, end=’ ’)
x=x%2
A) 9 7 5 3 1
B) 9 8 7 6 5 4 3 2 1
C) Infinite loop
D) 9 6 3 1
16. Which SQL operator performs pattern matching? 1
A) Between Operator
B) Like Operator
C) =
D) Equals operator
Q. 17 and 18 are ASSERTION (A) and REASONING (R) based questions
(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): List is an immutable data type. 1
Reasoning (R): When an attempt is made to update the value of an
immutable variable, the old variable is destroyed and a new variable is
created by the same name in memory.
18. Assertion (A): CSV is a file format for data storage which looks like a text 1
file.
Reasoning (R): The information is organized with one record in each line
and each field is separated by comma.
Section - B
19. (i) Write one difference between circuit switching and message 1+1=2
switching.
(ii) Expand the following terms
HTML, SMTP
OR
(i) Differentiate between hub and switch.
(ii) What is FTP?
20. The code given below is to add the digits of a number and display the sum 2
of the digits. Observe the code carefully and rewrite it after removing all
syntax and logical errors by underlining all the errors:
n=input("Enter a number")
S=0
while n<0:
s=s+n%10
n=n//10
print(“The sum of digits of the number:",s)

21. Write SQL commands to perform the following tasks 2


i) View the list of tables in the database School_db.
ii) View the structure of the table student.
22. Find the output of the following code. 2
t1=(11,22,33,44,55,66)
l1=list(t1)
new_list=[]

117 | P a g e
for i in l1:
if i%3==0:
new_list.append(i)
new_tuple=tuple(new_list)
print(new_tuple)
23. Differentiate between the tell() and seek() functions of file programming 2
24. What will be the output of the following code?
def add(n1,n2):
s=n1+n2
s=add(15,25)
print(s)

Or
list1=[10,15,20,25,30]
list1.insert(3,44)
list1.insert(2,33)
print(list1[-5])
25. Mr. Sarma created a table named car in a MySQL database, containing 2
car_id, car_name and car_company. Later he realized that the
attribute price has to be added. Help him to write command to add price
column. Thereafter, write command to insert the following record in the
table.
car_id= 101
car_name= NEXA
car_company= Maruti Suzuki
price= 350000

Section - C
26. Find and write the output of the following Python code: 3
List1=['40', '20', '30' , '50']
Count=3
Total=0
for c in [7,5,4,6]:
T=List1[Count]
Total = float(T)+c
print(Total)
Count=Count-1
27. Rakesh has a list containing 10 integers. Help him to create a program with 3
separate user defined functions to perform the following operations based
on the list.
 Traverse the content of the list and push the even numbers into a
stack
 Pop and display the content of the stack
For example:
If the sample content of the list is as follows:
N=[0,12,23,34,45,67,78,90,100,120]
Sample output of the code should be:
120 100 90 78 34 12 0
28. Find and write the output of the following Python code: 3
def changer (A,B=10):
A=A/B

118 | P a g e
B=A%B
print(A, '#', B)
return A

C=300
D=20

C=changer(C,D)
print(C, "$", D)
D=changer(D)
print(C, "$", D)
C=changer(C)
print(C, "$", D)
29. The code given below reads the following record from the table named 3
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:
 Username is root
 Password is tiger
 The table exists in a MYSQL database named school.

Write the following missing statements to complete the code: Statement 1


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

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root", password="tiger",
database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ # Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
30. Write a function AMcount() in Python, which should read each character 3
of a text file story.txt and count and display the occurrence or alphabets
A and M (including small cases)
Or
Write a function count() in python that counts number of “the” and “The”
present in a text file story.txt.
Section - D
31. A table, named STATIONERY, in ITEMDB database, has the following 4
structure:

119 | P a g e
Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)
Write the following Python function to perform the specified operation:
AddAndDisplay(): To input details of an item and store it in the table
STATIONERY. The function should then retrieve and display all records
from the STATIONERY table where the Price is greater than 120.

Assume the following for Python-Database connectivity:


Host: localhost, User: root, Password: Pencil

Or

Consider the tables Customer and Transaction given below:


Table: customer
Cno Cname Address
101 Raj Guwahati
102 Rahim Chennai
103 Karim Chennai
104 Tanushree Kolkata
105 Priyanka Delhi

Table: Transaction
Trno Cno Amount type Dot
T001 101 1500 Credit 2017-11-23
T002 103 2000 Debit 2017-05-12
T003 102 3000 Credit 2017-06-10
T004 103 12000 Credit 2017-09-12
T005 101 1000 Debit 2017-09-05

Write SQL queries for the following:


i) To display details of all transactions of type credit form table
transaction
ii) To display the last date of transaction from the table transaction
for the customer having cno as 103
iii) To display the transaction number, amount and date of
transaction of all transactions in descending order of amount.
iv) Display customer names and corresponding amounts for all
customers.

32. Rajkumar is a Python Programmer working in a school. He wanted to 4


maintain record of students. He has created a csv file named Student.csv
to store the details, which are as follows:
[S_id, S_name, S_class, S_house]
Where
S_id is the id of the student
S_name is the name of the student
S_class is the class in which the student is studying
S_house is the house allotted to the student

120 | P a g e
Now, Rajkumar wants to write the following user defines functions.
Complete these functions on behalf of him.
(i) Add_student(): to accept a record from the user and add it to
the csv file.
(ii) Count_student(): To count and display number of students
who belongs to Nilgiri House
Section - E
33. A software company has set up its new centre in Guwahati for its office and 5
web based activities. It has 4 blocks of building named Block A, Block B,
Block C, Block D. Number of computers:
Block A 25
Block B 50
Block C 125
Block D 10
Shortest distance between various blocks in meters:
Block A to Block B 60
Block B to Block C 40
Block C to Block A 30
Block D to Block C 50

(i) Name the most suitable block where the server should be
installed.
(ii) Suggest the type of network (topology) with diagram to connect
all the blocks with suitable reason.
(iii) The company is planning to link all the blocks through secure and
high-speed wired medium. Suggest a way to connect all the
blocks.
(iv) Suggest the most suitable wired medium for efficiently connecting
each computer installed in every block out of the following:
 Coaxial Cable
 Ethernet Cable
 Single Pair Telephone Cable
(v) What is the use of Ethernet cables?
34. (i) Mention any two differences between binary file and csv file. 5
(ii) Consider a binary file movie.dat containing multiple records of
movie in list. Each element of the movie contains the following
information
[moviename, time, rating]
Write a function high_rating() that reads the content of the file
and display the movies which have rating greater than or equal to
4.5.

OR
(i) Differentiate between r+ and w+ file modes in Python.
(ii) Consider a file, Sport.dat, containing records of the following
structure: [Sname, TeamName, Noofplayers]
Write a function copyData() that reads contents from the file
Sport.dat and copies the records with Sname ‘Football’ to the
file named Football.dat. The function should return the total
number of records copied to the file Football.dat.
35. Given the following tables for database Library 5

121 | P a g e
Table: Books
Book_id Book_name Author_name Publisher Price type Qty
C0001 Fast Cook Lata Kapoor EPB 355 Cookery 5
F0001 The tears William First pub 650 Fiction 20
Hopkins
T0001 My First Brain & EPB 350 Text 10
C++ Brooke
T0002 C++ A W TDH 350 Text 12
Solutions Rossaine
F0002 Thunderbolts Anna Roberts First pub 750 Fiction 50

Table: Issued
Book_id Quantity_issued
T0001 4
C0001 5
F0001 2
Give the output of the following queries:
i) Select count(*) from books;
ii) Select max(price) from books where quantity>=15;
iii) Select count(distinct publisher) from books where price>=400;
iv) Select book_name, author_name from books where publisher=’EPB’;
v) Write SQL query for increasing the price of all books published by
‘EPB’.
Or

Write SQL queries based on the following table


Table: Teacher

T_ID T_Name Subject DOJ Salary Workload Gender


101 Suresh English 12/03/2012 55000 20 F
103 Mithun History 12/06/2000 70000 22 M
104 Dhruba Computer 07/02/2014 60000 21 M
105 Madan English 06/06/2015 50000 F

i) To display the names of teacher teaching English.


ii) Display details of teachers in increasing order of salary.
iii) Display the name and salary of teacher with maximum workload.
iv) To display total number of teachers.
v) Increase the salary of History teacher by 10%.

******************** The End ************************

122 | P a g e
Answer Keys of the Practice Paper

Question Answer Remarks


No
1. B) 2024xyz
2. C) in
3. C) String
4. B) 24999
5. C) S[0]= ‘i’
6. B) r+
7. A) Record
8. D) Mega bits per second
9. B) It will merge all the elements of D2 in D1
10. C) Char
11. A) DNS
12. B) very have
13. d) Switch
14. A) Update
15. C) Infinite Loop
16. B) Like Operator
17. D
18. A
19. i) In circuit switching dedicated path for the entire
communication. Requires continuous connection and
inefficient. In message switching, no dedicated path. It
follow store and forward method of communication
ii) Hypertext Markup Language
Simple Mail Transfer Protocol
Or
i) Hub Broadcast data to all devices which is less efficient and
more collision prone. Switch sends data to the intended
device only which is more efficient and have fewer collision.
ii) FTP stands for File Transfer Protocol, and it is one of the
oldest and most commonly used methods for transferring
files over a network, particularly over the Internet.
20. n=int(input("Enter a number")) For every error
s=0 correction ½ marks
while n>0:
s=s+n%10
n=n//10
print("The sum of digits of the number:",s)
21. i) Use School_db; show tables;
ii) Describe student;
22. (33, 66)
23. tell() method returns an integer giving the current position of the
file pointer in the file where the integer represents the number of
bytes from the beginning of the file till the current position of the
file.
seek() method is used to position the file object at particular
place in the file. The syntax is fileobject. seek(offset, [from what])
24. None
Or
33

123 | P a g e
25. ALTER TABLE car ADD COLUMN price int;
INSERT INTO car VALUES (101, 'NEXA', 'Maruti Suzuki', 350000);
26. 57.0
35.0
24.0
46.0
27. def push(N):
for i in N:
if i%2==0:
stack.append(i)
def pop():
while stack:
print(stack.pop(),end=' ')
stack=[]
N=[0,12,23,34,45,67,78,90,100,120]

push(N)
pop()
28. 15.0 # 15.0
15.0 $ 20
2.0 # 2.0
15.0 $ 2.0
1.5 # 1.5
1.5 $ 2.0
29. Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from student where
Marks>75")
Statement 3: mycursor.fetchall()
30. f=open('story.txt')
c=0
data=f.read()

for i in data:
if i=='A' or i=='a' or i=='M' or i=='m':
c=c+1
print('Number of A and M in the file:',c)
Or
f=open('story.txt')
c=0
data=f.read()
data=data.split(' ')
for i in data:
if i=='the' or i=='The':
c=c+1
print('Number of the or The in the file:',c)
31. def AddAndDisplay():
import mysql.connector as mycon
mydb=mycon.connect(host="localhost",user="root",
passwd="Pencil",database="ITEMDB")
mycur=mydb.cursor()
no=int(input("Enter Item Number: "))
nm=input("Enter Item Name: ")
pr=float(input("Enter price: "))
qty=int(input("Enter qty: "))
query="INSERT INTO stationery VALUES ({},'{}',{},{})"

124 | P a g e
query=query.format(no,nm,pr,qty)
mycur.execute(query)
mydb.commit()
mycur.execute("select * from stationery where price>120")
for rec in mycur:
print(rec)
Or
i) Select * from transaction where type= ‘Credit’;
ii) Select max(dot) from transaction where cno= ‘103’;
iii) Select trno, amount, dot from transaction order by amount
desc.
iv) Select cname, amount from customer, transaction where
customer.cno=transaction.cno;
32. import csv
def Add_student():

S_id = input("Enter Student ID: ")


S_name = input("Enter Student Name: ")
S_class = input("Enter Student Class: ")
S_house = input("Enter Student House: ")

with open('Student.csv', mode='a', newline='') as file:


writer = csv.writer(file)
writer.writerow([S_id, S_name, S_class, S_house])

print("Student is added successfully!")

def Count_student():
count = 0
with open('Student.csv', mode='r') as file:
reader = csv.reader(file)
next(reader)

for row in reader:


if row[3].strip().lower() == 'nilgiri':
count += 1

print("Number of students in Nilgiri House: ",count)


33. (i) Block C since it has the maximum number of computers
(ii) LAN. Because network spans over a building
(iii) Star topology

(iv) Ethernet Cable


(v) Ethernet cables are used to provide an internet connection
an connect devices to a local network
34. i) Binary file stores data in binary format which is not human
readable. Binary file requires special software to interpret
CSV file stores data in plain text which is human readable.
It can be opened of viewed directly in text editors or

125 | P a g e
spreadsheets
ii) def high_rating():
print("This is the list of movies with rating greater
than 4.5")
f=open("movie.dat",'rb')
try:
while True:
data=pickle.load(f)
if data[2]>=4.5:
print(data)
except EOFError:
pass
f.close()
OR
i) r+ mode opens file for reading and writing. The file must
exist otherwise error will be shown. File pointer is placed at
the beginning of the file.
w+ mode opens a file in reading and writing. Creates a
new file if it does not exist, overwrites the file if it does.
The file pointer is placed at the beginning of the file.
ii) def copyData():
c=0
f1=open("Sport.dat",'rb')
f2=open("Football.dat",'rb')
try:
while True:
data=pickle.load(f1)
if data[0].lower()=='football':
pickle.dump(data,f2)
c=c+1
except EOFError:
pass
f1.close()
iii) f2.close()
iv) print("The total no of records copied:",c)
35. i) 5
ii) 750
iii) First Cook Lata Kapoor
My First C++ Brian & Brooke
iv) 1
v) Update books set price=price+50 where publishers= ‘EPB’;
Or
i) SELECT T_Name FROM Teacher WHERE Subject =
'English';
ii) SELECT * FROM Teacher ORDER BY Salary ASC;
iii) SELECT T_Name, Salary FROM Teacher WHERE Workload
= (SELECT MAX(Workload) FROM Teacher);
iv) SELECT COUNT(*) AS Total_Teachers FROM Teacher;
v) UPDATE Teacher SET Salary = Salary * 1.10 WHERE
Subject = 'History';

126 | P a g e
Questions on Database Management (UNIT-III)
Subject: Computer Science (083)
Class: XII

Section - A
1. In RDBMS, what do you mean by relation? 1
a) Row
b) Column
c) Table
d) Relationship
2. Which of the following in not a DML command? 1
a) Create
b) Select
c) Update
d) Insert
3. ________ is a set of attributes whose values are derived from primary 1
key of another table.
a) Primary Key
b) Candidate Key
c) Foreign Key
d) Alternate Key
4. No of rows in a table is called_____________ 1
5. No of columns in a table is called _______________ 1
6. Which of the following types of table constraints will prevent the entry 1
of duplicate rows?
a) Unique Key Constraints
b) Primary key Constraints
c) Distinct Key Constrains
d) Referential Key Constraints
7. What are the mandatory arguments required to connect MYSQL with 1
Python
a) Username, Password, Hostname, Database Name, Port
b) Username, Password, Hostname
c) Username, Password, Hostname, Port
d) Username, Password, Hostname, Database Name
8. Which of the following method reflects the permanent change in the 1
Database?
a) <connection>.final()
b) <connection>.complete()
c) <connection>.commit()
d) <connection>.flush()
9. What is the function that is used to get all the records from the result 1
set?
a) cursor.fetchmany()
b) cursor.fetchall()
c) cursor.fetchevery()
d) cursor.fetchmulty()
10. Tuple represents a _______ in a table 1
a) Row
b) Column 1
c) Attributes

127 | P a g e
d) Fields
11. SQL stands for 1
a) Standard Query Language
b) Structured Query Language
c) Short Query Language
d) Server Queried Language
12. Which of the following command is used to modify the structure of the 1
Table in a database?
a) Modify
b) Update
c) Alter
d) Update
13. Write a query to display the records of all the student table, whose 1
name contains a substring ‘ta’.
a) Select * from student where sname like “ta”;
b) Select * from student where sname like “%ta%”;
c) Select * from student where sname like %“ta”%;
d) Select * from student where sname like “---ta%”;
14. ____________ is used to delete one or more records from a database 1
table?
a) Delete
b) Remove
c) Del
d) Clear
15. Write a query to display the records of employees whose salary in 1
unknown.
a) Select * from employee where salary is null;
b) Select * from employee where salary=null;
c) Select * from employee whose salary is null;
d) Select * from employee whose salary like ‘null’;
16. Which of the following aggregate functions returns the sum of the 1
values for the specified columns?
a) Sum()
b) Add()
c) All()
d) Count()
Q. 17 and 18 are ASSERTION (A) and REASONING (R) based questions
(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 HAVING clause is used with aggregate functions. 1
Reason (R) : WHERE clause places conditions on individual rows.
18. Assertion (A) : The number of attributes in a relation is called the 1
Degree of the relation.
Reason (R) : The number of rows in the table is called cardinality of the
relation.
Section – B
19. a) Differentiate between char and varchar. 2

128 | P a g e
b) Differentiate between degree and cardinality.
OR
a) Differentiate between candidate key and primary key.
b) Differentiate between alternate key and primary key.
20. a) Differentiate between DML and DDL. 2
b) What do you mean by data redundancy?
OR
a) Differentiate between alter and update commands.
b) What do you mean by data inconsistency?
21. i) What constraint should be applied on a table column so that 2
duplicate values are not allowed in that column, but NULL is
allowed?
ii) What constraint should be applied on a table column so that
NULL is not allowed in that column, but duplicate values are
allowed.
22. Categorise the following commands as DDL and DML 2
Alter, Update, Drop, Delete
23. Rashmi is using a table Employee. It has the following columns: 2
Code, Name, Salary, DeptCode

She wants to display maximum salary department wise. She wrote the
following command but did not get the desired result.
Select DeptCode, max(salary) from employee;

Rewrite the above query with necessary changes to help him get the
desired output.
24. Explain Candidate Key, Primary Key, Alternate Key and Foreign key 2
with example
Or
Explain with example the degree and cardinality of a relation in RDBMS.
25. Write four advantages of database management system. 2
Or
Write four DML commands and four DDL commands.
Section – C
26. Ganesh want to create a database named mydb1 with a table named 3
city. The table city has the following structure:
Field Name Data Type Remarks
Citycode Char (5) Primary Key
Cityname varChar(30)
Size Integer
Population Integer
Pollution rate float

Help him to complete the task by suggesting appropriate SQL


commands.
27. The code given below reads the following record from the table named 3
student and displays only those records who have marks greater than
75:
RollNo – integer
Name – string
Clas – integer

129 | P a g e
Marks – integer
Note the following to establish connectivity between Python and
MYSQL:
 Username is root
 Password is tiger
 The table exists in a MYSQL database named school.

Write the following missing statements to complete the code:


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

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
28. Differentiate between fetchall(), fetchmany(n) and fetchone(). 3
29. What is join? Also, define equi-join and natural join with example. 3
30. The code given below inserts the following record in the table Student: 3
RollNo – integer
Name – string
Class – integer
Marks – integer
Note the following to establish connectivity between Python and
MYSQL:
 Username is root
 Password is tiger
 The table exists in a MYSQL database named school
 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
Statement 2 – to execute the command that inserts the record in the
table Student.
Statement 3- to add the record permanently in the database

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host= ”localhost", user="root",
password="tiger", database= "school")
mycursor=_________________ #Statement 1
rno=int(input("Enter Roll Number :: "))

130 | P a g e
name=input("Enter name :: ")
class=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values({},'{}',{},{})".format(rno,
name, class, marks)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
Section - D
31. A table, named STATIONERY, in ITEMDB database, has the following 4
structure:
Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)
Write the following Python function to perform the specified operation:
AddAndDisplay(): To input details of an item and store it in the table
STATIONERY. The function should then retrieve and display all records
from the STATIONERY table where the Price is greater than 120.

Assume the following for Python-Database connectivity:


Host: localhost, User: root, Password: Pencil
32. Consider the tables Customer and Transaction given below: 4
Table: customer
Cno Cname Address
101 Raj Guwahati
102 Rahim Chennai
103 Karim Chennai
104 Tanushree Kolkata
105 Priyanka Delhi

Table: Transaction
Trno Cno Amount type Dot
T001 101 1500 Credit 2017-11-23
T002 103 2000 Debit 2017-05-12
T003 102 3000 Credit 2017-06-10
T004 103 12000 Credit 2017-09-12
T005 101 1000 Debit 2017-09-05

Write SQL queries for the following:


i) To display details of all transactions of type credit form table
transaction
ii) To display the last date of transaction from the table
transaction for the customer having cno as 103
iii) To display the transaction number, amount and date of
transaction of all transactions in descending order of amount.
iv) Display customer names and corresponding amounts for all
customers.

Section - E

131 | P a g e
33. Write SQL queries based on the following table 5
Table: Teacher

T_ID T_Name Subject DOJ Salary Workload Gender


101 Suresh English 12/03/2012 55000 20 F
103 Mithun History 12/06/2000 70000 22 M
104 Dhruba Computer 07/02/2014 60000 21 M
105 Madan English 06/06/2015 50000 F

i) To display the names of teacher teaching English.


ii) Display details of teachers in increasing order of salary.
iii) Display the name and salary of teacher with maximum
workload.
iv) To display total number of teachers.
v) Increase the salary of History teacher by 10%.
34. Given the following tables for database Library 5
Table: Books
Book_id Book_name Author_name Publisher Price type Qty
C0001 Fast Cook Lata Kapoor EPB 355 Cookery 5
F0001 The tears William First pub 650 Fiction 20
Hopkins
T0001 My First Brain & EPB 350 Text 10
C++ Brooke
T0002 C++ A W TDH 350 Text 12
Solutions Rossaine
F0002 Thunderbolts Anna Roberts First pub 750 Fiction 50

Table: Issued
Book_id Quantity_issued
T0001 4
C0001 5
F0001 2
Give the output of the following queries:
i) Select count(*) from books;
ii) Select max(price) from books where quantity>=15;
iii) Select count(distinct publisher) from books where
price>=400;
iv) Select book_name, author_name from books where
publisher=’EPB’;
v) Write SQL query for increasing the price of all books
published by ‘EPB’.
35. Write SQL queries/ answer the following based on the table given 5
below:
Table: GIProduct

CerNo Product Type District State DOR


643 Judima Manufactured Dima Hasao Assam 12/12/2024
939 Majuli Mask Handicraft Majuli Assam 12/10/2015
of Assam

438 Tezpur Manufactured Sonitpur Assam 10/10/2013


Litchi

132 | P a g e
435 Kabri Agricultural Karbi Assam 10/05/2010
Anglong Anglong
Ginger

i) What is the Degree and Cardinality of the above table?


ii) To display the product and district of the manufactured GI
items.
iii) To display the name and type of the product in descending
order of the date when the product is recognised?
iv) To display number of product to be recognised district wise.
v) To display total number of product recognised in the State of
Assam

133 | P a g e
Database Management
Class: XII
Subject: Computer Science
Answer Keys
1. c) Table
2. a) Create
3. c) Foreign Key
4. Cardinality
5. Degree
6. b) Primary Key Constraint
7. d) Username, Password, Hostname, Database Name
8. c) <connection>. commit()
9. b) cursor.fetchall()
10. a) Row
11. b) Structured Query Language
12. c) Alter
13. b) select * from student where sname like “%ta%”;
14. a)Delete
15. c)select * from employee whose salary is null;
16. a) Sum()
17. B
18. B
19. a) CHAR stores data in a fixed-length field, while
VARCHAR stores data in a variable-length field
CHAR can be slightly faster for fixed-length strings
because the database knows the exact size of each entry.
It doesn't need to track the string length for each value.
VARCHAR is more efficient in terms of storage when
the string lengths vary significantly, but it may require
extra overhead for managing the length of the variable-
length entries.
b) Degree: Number of columns/ fields/ attributes in a
relation
Cardinality: Number of rows/ tuples/ records in a relation
Or
a) Candidate Key: A set of one or more columns that
can uniquely identify a record in a table. A table can have
multiple candidate keys.
Primary Key: A special candidate key that is chosen to
uniquely identify records in the table. There can only be
one primary key per table.
b) Primary Key: The unique key selected to identify
records in a table; it enforces uniqueness and does not

134 | P a g e
allow null values. There is only one primary key
Alternate Key: A candidate key that was not selected as
the primary key but could still uniquely identify records in
the table. There can be multiple alternate keys.

20. a) DML:
 Does not affect the database schema; it only
works with the data stored in the tables.
 Example: INSERT INTO Employees VALUES ('John',
'Smith') (adds data but doesn’t alter table
structure).
DDL:
 Affects the database schema; it changes the
structure of tables or other database objects.
 Example: CREATE TABLE Employees (ID INT,
Name VARCHAR(100)) (creates a new table
structure).
b) Data Redundancy refers to the unnecessary
duplication of data within a database or system. It
occurs when the same piece of information is stored in
multiple places, leading to inefficiency in storage and
potential inconsistency.
Or
a) ALTER: Used to modify the structure of a database
object (like a table), such as adding, deleting, or
modifying columns, or changing constraints.
UPDATE: Used to modify the data within existing
records in a table
b) Data Inconsistency refers to a situation where the
same piece of data stored in multiple places in a system
or database does not match
21. i) Unique
ii) Not null
22. DDL: Alter, Drop
DML: Update, Delete
23. Select DeptCode, max(salary) from employee group by
DeptCode;
24. Candidate Key: A set of columns that can uniquely
identify records (e.g., StudentID, PhoneNo).
Primary Key: The selected candidate key to uniquely
identify records, cannot be null (e.g., StudentID).
Alternate Key: Candidate keys not chosen as the
primary key (e.g., PhoneNo).
Foreign Key: References the primary key in another

135 | P a g e
table to establish relationships
Or
Degree = Number of attributes (columns) in a table.
Cardinality = Number of tuples (rows) in a table
25. Reduces Data Redundancy: Centralizes data
storage to avoid duplication.
Ensures Data Integrity: Enforces rules for accurate
and consistent data.
Improves Data Security: Provides access control
and user authentication.
Enhances Data Management: Optimizes data
retrieval, updating, and deletion
Or
DML : Select, insert, update, delete
DDL : Create, alter, drop, rename
26. Create database mydb1;
Create table city
(
Citycode char(5),
Cityname varchar(30),
Size int,
Population int,
Pollution float
);
27. Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from student
where Marks>75")
Statement 3: mycursor.fetchall()
28. fetchall() : Returns a sequence of all the rows that have
not been fetched.
fetchmany() : Returns a sequence of rows specified by n
fetchone() : Returns the next row of the query result set
as a sequence or none when the result is exhaused
29. Equi-Join: Joins tables using a specific column with the
= operator (explicit join condition).
Natural Join: Joins tables based on columns with the
same name and matching data types (implicitly uses
common columns for the join).
30. Statement 1: con1.cursor()
Statement 2: mycursor.execute(querry)
Statement 3: con1.commit()
31. def AddAndDisplay():
import mysql.connector as mycon
mydb=mycon.connect(host="localhost",user="root",

136 | P a g e
passwd="Pencil",database="ITEMDB")
mycur=mydb.cursor()
no=int(input("Enter Item Number: "))
nm=input("Enter Item Name: ")
pr=float(input("Enter price: "))
qty=int(input("Enter qty: "))
query="INSERT INTO stationery VALUES
({},'{}',{},{})"
query=query.format(no,nm,pr,qty)
mycur.execute(query)
mydb.commit()
mycur.execute("select * from stationery where
price>120")
for rec in mycur:
print(rec)
32. i) Select * from transaction where type= ‘Credit’;
ii) Select max(dot) from transaction where cno= ‘103’;
iii) Select trno, amount, dot from transaction order by
amount desc.
iv) Select cname, amount from customer, transaction
where customer.cno=transaction.cno;
33. i) SELECT T_Name FROM Teacher WHERE Subject =
'English';
ii) SELECT * FROM Teacher ORDER BY Salary ASC;
iii) SELECT T_Name, Salary FROM Teacher WHERE
Workload = (SELECT MAX(Workload) FROM
Teacher);
iv) SELECT COUNT(*) AS Total_Teachers FROM
Teacher;
v) UPDATE Teacher SET Salary = Salary * 1.10
WHERE Subject = 'History';
34. i) 5
ii) 750
iii) First Cook Lata Kapoor
My First C++ Brian & Brooke
iv) 1
v) Update books set price=price+50 where
publishers= ‘EPB’;
35. i) Degree: 6 Cardinality: 4
ii) SELECT Product, District FROM GIProduct WHERE
Type = 'Manufactured';
iii) ELECT Product, Type FROM GIProduct ORDER BY DOR
DESC;
iv) SELECT District, COUNT(*) AS Number_of_Products

137 | P a g e
FROM GIProduct GROUP BY District;
v) SELECT COUNT(*) AS Total_Products_in_Assam
FROM GIProduct WHERE State = 'Assam';

138 | P a g e
PRACTICE PAPER
Computer Science (083)
Class XII (2024-25)
Time Allowed: 3 hours Maximum Marks: 70
General Instructions:
a. This question paper contains 37 questions.
b. All questions are compulsory. However, internal choices have been provided in some questions.
Attempt only one of the choices in such questions. The paper is divided into 5 Sections- A, B, C, D and
E.
c. Section A consists of 21 questions (1 to 21).
d. Each question carries 1 Mark. Section B consists of 7 questions (22 to 28).
e. Each question carries 2 Marks. Section C consists of 3 questions (29 to 31).
f. Each question carries 3 Marks. Section D consists of 4 questions (32 to 35).
g. Each question carries 4 Marks. Section E consists of 2 questions (36 to 37).
h. Each question carries 5 Marks.
i. All programming questions are to be answered using Python Language only.
j. In case of MCQ, text of the correct answer should also be written

Section-A (21 x 1 = 21 Marks)

1 State true or false:


(1)
The expression 2**2**3 is evaluated as: (2**2)**3

2 Fill in the blank.


________ is a number of fields in a relation.
(1)
a)Domain b)Cardinality
c)Attribute d)Degree

3 What will be the output of following code if a = "abcde".


>>> a[1:1] == a[1:2] (1)
>>> type(a[1:1]) == type(a[1:2])

4 What is the output of following code?


L = [[4,1],[2,3],[3,5],[6,0.5]]
L.sort()
(1)
print(L)
a)[[2,3],[3,5],[4,1],[6,0.5]] b)[[2,3],[3,4],[5,6]]
c)[[0.5,1],[2,3],[3,4],[5,6]] d)[[6,0.5],[4,1],[2,3],[3,5]]

5 What is the output of the following expression?


(1)
print([4.00/(2.0 + 2.0),4.00/2.0 + 2.0,4.00/2.0/2.0])

6 Fill in the blank:


The protocol used for remote login is _____________
(A) FTP (1)
(B) Telnet
(C) HTTP

139 | P a g e
(D) IRCP

7 Which of the following command is used to open a file "c:\pattxt" for writing in
binary format only?
(1)
a)fout = open("c:\\pat.txt", "wb") b)fout = open("c: \pat.txt", "w+")
c)fout = open("c:\ \pat.txt","wb+") d)fout = open(“c: \ pat.txt”, “w”)

8 Which library is used to connect Python with MySQL?


a)SQL.connect library b)MySQL.connector library (1)
c)MySQL.connect library d)MySQL.connect library

9 Which of the following group functions ignore NULL values?


a)MAX b)All of these (1)
c)SUM d)COUNT

10 How are following codes different from one another?


i. my_file = open('poem.txt', 'r')
my_file.read() (1)
ii. my_file = open('poem.txt', 'r')
my_file.read(100)

11 State true or false:


There can be only a single except block against a try block. (1)

12 When a stack, implemented as an array/list of fixed size, is full and no new element
can be accommodated, it is called an ________.
(1)
a)OVERFLOW b)NOFLOW
c)EXTRAFLOW d)UNDERFLOW

13 Which of the following statement(s) would give an error during execution of the following
code? tup = (20, 30, 40, 50, 80, 79)
print (tup) #Statement 1
print (tup [3]+50) #Statement 2
print (max (tup)) #Statement 3
(1)
tup [4]=80 #Statement 4
(A) Statement 1
(B) Statement 2
(C) Statement 3
(D) Statement 4

14 Fill in the blank :


In ________ switching, before a communication starts, a dedicated path is
identified between the sender and the receiver. (1)
a)Circuit b)Packet
c)Plot d)Graph

15 Consider the code given below: (1)

140 | P a g e
b = 100
def test (a):
___________ #missing statement
b=b+a
print (a, b)
test (10)
print (b)
Which of the following statements should be given in the blank for #Missing Statement, if
the output produced is 110?
(A) global a
(B) global b=100
(C) global b
(D) global a=100

16 Which of the following command is used to remove the table definition and all data?
a)Choose b)Drop (1)
c)Create d)Select

17 What possible outputs(s) will be obtained when the following code is executed?
import random
myNumber = random. randint (0, 3)
COLOR = ["YELLOW", "WHITE", "BLACK", "RED"]
for I in COLOR:
for J in range (1, myNumber):
print (I, end="*")
print ()
options:
A. RED*
WHITE*
BLACK*
RED* (1)
B. YELLOW*
WHITE*
BLACK*
RED*
C. WHITE* WHITE *
YELLOW *YELLOW*
BLACK* BLACK*
RED* RED*
D. YELLOW*
WHITE *WHITE *
BLACK* BLACK *BLACK*
RED *RED* RED *RED* RED*

141 | P a g e
18 The ________ translates internet domain and hostnames to IP address.
a)internet relay chat b)routing information protocol (1)
c)network time protocol d)domain name system

19 What is the meaning of "HAVING" clause in SELECT query?


a)To filter out the row groups b)To filter out the column groups (1)
c)To filter out the row values d)To filter out the row and column values

Q20 and Q21 are Assertion (A) and Reason(R) based questions. Mark the correct
choice as:
a)Both A and R are true and R is the correct explanation of A.
b)Both A and R are true but R is not the correct explanation of A.
c)A is true but R is false.
d)A is false but R is true.

20 Assertion (A): To store the data permanently into the file we use file handling.
Reason (R): A file is a named location on a disk to store related information.
a)Both A and R are true and R is the correct explanation of A.
(1)
b)Both A and R are true but R is not the correct explanation of A.
c)A is true but R is false.
d)A is false but R is true.

21 Assertion (A): SQL SELECT’s GROUP BY clause is used to divide the result in groups.
Reason (R): The GROUP BY clause combines all those records that have identical in a (1)
particular fields or in group by fields

Section-B ( 7 x 2=14 Marks)

22 Observe the given list and find the answer of questions that follows.
list1 = [23, 45, 63, ‘Hello’, 20
(2)
‘World’, 15, 18]
(i) list1[–3] (ii) list1[3]

23 Write function names for the following with respect to strings.


(i) To make the first letter of a string in capital (2)
(ii) To find the index of the 1st occurrence of a string in another

142 | P a g e
24
Find the errors in following code and write the correct code.
Def s(x):
a = ‘k'
print(a * x)
print(a * str(x))
for in [1, 2', 10 :
s(n)
i. Underline the corrections
ii. Write the reason!error next to it in comment form. (2)
OR
How can you add following data in an empty dictionary?
Keys Values

A One

B Two

C Three
D Four

25 What is the output of the following Python code snippet?


string=”Hello, World!”
print(string[ : : -1])

a) “Hello, World!”
(2)
b) “dlroW ,olleH”

c) “World! Hello,”

d) “olleH ,dlroW”

26 Rewrite the following code into for loop:


i=3
while (i < 5):
if (i == 4):
print("Welcome") (2)
else:
print("No entry")
i=i+1
print(“value of i”, i)

27 A SQL table ITEMS contains the following columns:


INO,INAME,QUANTITY,PRICE,DISCOUNT
(2)
(i)Write5 the SQL command to remove the column DISCOUNT from the table.
(ii)Categorise the following commands into DDL and DML: CREATE,UPDATE,INSERT,DROP

143 | P a g e
28 Write 2 advantages and 2 disadvantage of bus topology.
OR (2)
How is Coaxial cable different from Optical Fibre?

Section-C ( 3 x 3 = 9 Marks)

29 Write a method Filterwords() to find and display words from a text file ‘NewsLetter.txt’
whose length is less than 4.
OR (3)
Write a method countAN() that checks the number of occurrance of “A” and “N” in a text file
“Story.txt”.

30 Write the Push operation of stack containing person names. Notice that the name
should only accept characters, spaces and period (.) except digits. Assume that
Pname is a class instance attribute.
OR (3)
A line of text is read from the input terminal into a stack. Write a program to output the
string in the reverse order, each character appearing twice.
(ie.g., the string a b c d e should be changed to ee dd cc bb aa)

31 Give the output of the Python code snippet :


L1=[500,800,600,200,900]
START=1
SUM=0
for C in range(START,4)
SUM=SUM+L1[C]
print(C,”:”,SUM)
SUM=SUM+L1[0]*10
print(SUM)
OR (3)
dct={}
dct[1]=1
dct[‘1’]=2
dct[1.0]=4
sum=0
for k in dct:
print(k,sum)
sum+=dct[k]
print(sum)

Section-D ( 4 x 4 = 16 Marks)

144 | P a g e
32 (A)Write SQL queries for (i) to (iv)
Which are based on the table.
TABLE: ACCOUNT

ANO ANAME ADDRESS

101 Nirja Singh Bangalore

102 Rohan Gupta Chennai

103 Ali Reza Hyderabad

104 Rishabh Jain Chennai

105 Simian Kaur Chandigarh

TABLE: TRANSACT

TRNO ANO AMOUNT TYPE DOT

T001 101 2500 Withdraw 2017-12-21

T002 103 3000 Deposit 2017-06-01


(4)
T003 102 2000 Withdraw 2017-06-12

T004 103 1000 Deposit 2017-10-22

T005 101 12000 Deposit 2017-11-06

i. To display details of all transactions of TYPE Deposit from Table TRANSACT.


ii. To display the ANO and AMOUNT of all Deposits and Withdrawals done in the
month of October 2017 from table TRANSACT.
iii. To display the last date of transaction (DOT) from the table TRANSACT for the
Accounts having ANO as 103.
iv. To display all ANO, ANAME and DOT of those persons from tables ACCOUNT and
TRANSACT who have done transactions less than or equal to 3000.
OR
(B) find outputs for SQL queries (i) to (iv)
i. SELECT ANO, ANAME FROM ACCOUNT WHERE ADDRESS NOT IN (CHENNAI
BANGALORE);
ii. SELECT DISTINCT ANO FROM TRANSACT;
iii. SELECT ANO. COUNT (*), MIN (AMOUNT) FROM TRANSACT GROUP BY ANO
HAVING COUNT (*) > 1;
iv. SELECT COUNT (*), SUM (AMOUNT) FROM TRANSACT WHERE DOT <= '2017-06-
01';

33 Write one difference between CSV and text files.


Write a program in Python that defines and calls the following user defined
functions:
i. COURIER_ADD () : It takes the values from the user and adds the details to a csv file (4)
'courier.csv'. Each record consists of a list with field elements as cid, sname, Source,
destination to store Courier ID, Sender name, Source and destination address
respectively.
ii. COURIER_SEARCH () : Takes the destination as the input and displays all the

145 | P a g e
courier records going to that destination.

34 Consider the following tables GAMES and PLAYER and answer (b) and (c) parts of this
question:
Table: GAMES

GCode Game Name Type Number Prize Money Schedule Date


101 Carom Board Indoor 2 5000 23-Jan-2004
102 Badminton Outdoor 2 12000 12-Dec-2003
103 Table Tennis Indoor 4 8000 14-Feb-2004 (4)
105 Chess Indoor 2 9000 01-Jan-2004
108 Lawn Tennis Outdoor 4 25000 19-Mar-2004
Write SQL commands for the following statements:
i. To display the name of all GAMES with their GCodes.To display details of those
ii. GAMES which are having PrizeMoney more than 7000.
iii. To display the content of the GAMES table in ascending order of ScheduleDate.
iv. To display sum of PrizeMoney for each type of GAMES.

35
Create following table using Python code where
Database - Test
Table - Watches
User name - Root
Password – System
(4)
Watchld WatchName Price Type Qtystore
W001 High Time 10000 Unisex 100
W002 Life Time 5000 Ladies 150
W003 Wave 20000 Gents 200
W004 High Fashion 7000 Unisex 250
W005 Golden Time 25000 Gents 100

SECTION E (2 X 5 = 10 Marks)

36 What are the advantages of CSV files?


Write a python program using following functions to :
A file “teacher.csv” contains a city, teacher name and Salamount.
(a) Search() : Search and print all rows where city is “delhi”.
Sample “teacher.csv” :
City Teacher Name Salamount
Delhi, Anil Sharma, 10000 (5)
Pune, Mr Dua, 20000
Delhi, Mr Das, 25000
(b) Searchfromfile() : From the file “teacher.csv” print all rows where teacher name is
“Anil”.
OR
What are the Disadvantages of CSV files?

146 | P a g e
Write a program using functions :
(a) addTransaction() : To append bank transactions of following structure to “bank.csv”
TranlD TranDate Amount Type
(b) getTran() : To display those transactions whose type is “Deposit”.

37 The Freshminds University of India is starting its first campus in Ana Nagar of South India
with its center admission office in Kolkata. The university has 3 major blocks comprising of
Office Block, Science Block and Commerce Block in the 5km area Campus.

As a network expert, you need to suggest the network plan as per (i) to (iv) to the
authorities keeping in mind the distance and other given parameters.
Expected Wire distances between various locations:

Office Block to Science Block 90 m

Office Block to Commerce Block 80 m

Science Block to Commerce Block 15 m

Kolkata Admission office to Ana Nagar Campus 2450 km


(5)
Expected number of Computers to be installed at various locations in the University are as
follows:

Office Block 10
Science Block 140
Commerce Block 30
Kolkata Admission office 8
i. What type of server should be installed in university?
Dedicated
Non-dedicated
ii. Suggest a suitable cable layout of connectivity of the blocks of university campus.
iii. Suggest the most suitable place (i.e., block) to house the server of this university
with a suitable reason.
iv. Suggest an efficient device from the following to be installed in each of the blocks to
connect all the computers:
MODEM
SWITCH
GATEWAY
v. Suggest the most suitable (very high speed) service to provide data connectivity
between Admission Office located in Kolkata and the campus located in Ana Nagar

147 | P a g e
from the following options:
Telephone line
Fixed-Line Dial-up connection
Co-axial Cable Network
GSM
Leased line
Satellite Connection

148 | P a g e
PRACTICE PAPER
(MARKING SCHEME)
Computer Science (083)
Class XII (2024-25)
Time Allowed: 3 hours Maximum Marks: 70
General Instructions:
a. This question paper contains 37 questions.
b. All questions are compulsory. However, internal choices have been provided in some questions.
Attempt only one of the choices in such questions. The paper is divided into 5 Sections- A, B, C, D and
E.
c. Section A consists of 21 questions (1 to 21).
d. Each question carries 1 Mark. Section B consists of 7 questions (22 to 28).
e. Each question carries 2 Marks. Section C consists of 3 questions (29 to 31).
f. Each question carries 3 Marks. Section D consists of 4 questions (32 to 35).
g. Each question carries 4 Marks. Section E consists of 2 questions (36 to 37).
h. Each question carries 5 Marks.
i. All programming questions are to be answered using Python Language only.
j. In case of MCQ, text of the correct answer should also be written

Section-A (21 x 1 = 21 Marks)

1 false: (1)

2 d)Degree (1)

3 The output produced by given code will be:


False , a[1:1] , a[1:2] value is different (1)
True a[1:1] , a[1:2] is same type

4 (a) [[2,3],[3,5],[4,1],[6,0.5]] (1)

5 [1.0, 4.0, 1.0] (1)

6 (B) Telnet (1)

7 a)fout = open("c:\\pat.txt", "wb") (1)

8 b)MySQL.connector library (1)

9 b)All of these (1)

10 i. read() method will read all the contents of the file poem.txt.
(1)
ii. read(100) will only read the first 100 bytes of the file poem.txt.

11 false: (1)

12 a)OVERFLOW (1)

13 (D) Statement 4 (1)

14 a)Circuit (1)

15 (1)
(C) global b

149 | P a g e
16 b)Drop (1)

17 B. YELLOW*
WHITE*
BLACK* (1)
RED*

18 d)domain name system (1)

19 a)To filter out the row groups (1)

20 (b) Both A and R are true but R is not the correct explanation of A.
Explanation:
The file handling plays an important role when the data needs to be stored permanently in (1)
the file. A file is a named location on a disk to store related information.

21 a)Both A and R are true and R is the correct explanation of A. (1)

Section-B ( 7 x 2=14 Marks) (1)

22 (i) World (ii) Hello (1)

23 Write function names for the following with respect to strings.


(i) capitalize() (1)
(ii) index()

24 def s(x): # def should be in lowercase


a = 'k'
print(a*x)
print(a + str(x)) # two strings cannot be used with * operator,
for n in [1, 2, 10 ]: # but can use -f operator
# (i) loop variable not defined
# (ii) closing ] missing
s(n) # incorrect indentation (1)
OR
dic = { }
dic[‘A’] = 'One'
dic[‘ B’] = 'Two'
dic[‘C’] = 'Three'
dic[‘D’] = 'Four’

25 (1)
b) “dlroW ,olleH”

26 for I in range(3,5):
if (i == 4):
print("Welcome")
else:
print("No entry")
print(“value of i”, i)

27 (i)ALTER TABLE Items DROP COLUMN Discount;


(ii) DDL: CREATE, DROP

150 | P a g e
DML: UPDATE,INSERT

28 Write 2 advantages:
1. Low Cost
2. Easy to Expand
2 disadvantage
1. Single Point failure
2. Limited cable length
OR
Optical fibre and Coaxial cables, both are different types of guided media cables. Optical
fibre is made up of plastic and glass and is used to transmit signals in form of light or optics
whereas coaxial cable is made using plastic and copper wires and is used to transmit
signals in form of electric signals.

Section-C ( 3 x 3 = 9 Marks)

29 def Filterwords():
c=0
file=open('NewsLetter.txt', 'r')
line=file.read()
word=line.split('')
for c in word:
if len(c)<4:
print(c)
file.close()
OR
def countAN():
countA-C
countN=0
file=open ("Story.txt", "r")
data-file.read()
for ch in data:
if ch in "A":
countA+=1
elif ch in "N"
countN+=1
print("Number of A:", countA)
print("Number of N:", countN)
file.close()

30 def insert():
name_pattern = re.compile(r"[A-Za-zs.]")
while True:
n = input("Enter name:")
while name_pattern.search(n):
print("Invalid name")

151 | P a g e
print("Enter name correctly")
n = input()
Sname.append(n)
c = input("Enter more name <y/n>").upper()
if (c!='y'):
break
OR
s = input('Enter a string : ')
stack = []
for i in s:
stack.append(i)
l= len(stack)
for i in range(l):
print(stack.pop()*2, end="")
print()

31 1:800
5800
2:6400
11400
3:11600
16600
OR
6

Section-D ( 4 x 4 = 16 Marks)

32 (A)
i. SELECT * FROM TRANSACT WHERE TYPE = 'Deposit' ;
ii. SELECT ANO , AMOUNT FROM TRANSACT WHERE DOT > = ' 2017-10-01 'AND DOT
< = '2017-10-31';
iii. SELECT DOT FROM TRANSACT WHERE ANO = 103 ORDER BY DOT DESC LIMIT =1;
iv. SELECT A.ANO, ANAME, DOT FROM ACCOUNT A, TRANSACT T WHERE A.ANO =
T.ANO AND AMOUNT <= 3000;
OR
(B) find outputs for SQL queries (i) to (iv)

i. ANO ANAME

103 Ali Reza

105 Simran Kaur

DISTINCT ANO

101

102

103

iii.

152 | P a g e
ANO COUNT(*) MIN(AMOUNT)
101 2 2500
103 2 1000
iv.
COUNT (*) SUM(AMOUNT)
2 5000

33 CSV files
 can be viewed in spreadsheets
 module CSV has to be imported
Text files
 can be viewed in the text editor
 No specific module required to be imported

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

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

34 i. SELECT GameName, GCode FROM GAMES;


ii. SELECT * FROM Games WHERE PrizeMoney > 7000;
iii. SELECT * FROM Games ORDER BY ScheduleDate;
iv. SELECT SUM(Prizemoney) FROM Games GROUP BY Type;

153 | P a g e
35 import mysql.connector
my=mysql.connector.connect(host="localhost",
user="Root",
password="System",
database=”test”)
cursor=my.cursor()
db=cursor.execute("CREATE TABLE Watches (Watch_Id varchar(5) Primary Key,
WatchName varchar(10), Price int(6),Type(6),Qtystore int(3);)
sql = "INSERT INTO Watches(WatchId, WatchName, Price, Type, Qty_store) VALUES (%
val=[("W001", "High Time", 10000, "Unisex", 100),("W002", "Life Time", 5000,
"Ladies”,150), ("W003", "Wave", 20000, "Gents", 200),("W004", "High fashion", 7000,
"Unisex”,250), ("W005", "GoldenTime", 250000, "Gents", 100)]
try:
cursor.executemany(sql, val)
my.commit();
except:
my.rollback()
my.close()

SECTION E (2 X 5 = 10 Marks)

36 What are the advantages of CSV files?


Write a python program using following functions to :
A file “teacher.csv” contains a city, teacher name and Salamount.
(a) Search() : Search and print all rows where city is “delhi”.
Sample “teacher.csv” :
City Teacher Name Salamount
Delhi, Anil Sharma, 10000
Pune, Mr Dua, 20000
Delhi, Mr Das, 25000
(b) Searchfromfile() : From the file “teacher.csv” print all rows where teacher name is
“Anil”.
OR
What are the Disadvantages of CSV files?
Write a program using functions :
(a) addTransaction() : To append bank transactions of following structure to “bank.csv”
TranlD TranDate Amount Type
(b) getTran() : To display those transactions whose type is “Deposit”.

37 i. The server should be Dedicated server

ii.
Office Commerce
Block Block

Science
Block

154 | P a g e
iii. The most suitable place to house the server is Science Block as it has the maximum
number of computers. Thus, reducing the cabling cost and increase the efficiency of
the network.
iv. SWITCH
v. Satellite Connection Or Leased line

155 | P a g e
COMPUTER NETWORKS
MM: 60 Maximum
Time: 1h 30 mins

Objective Type Question 1x15=15


1. Which topology is based on a central node which act as a hub?
(A) Star topology (B) Bus topology
(C) Tree topology (D) Hybrid topology
2. Which of the following is not a network device?
(A) Modem (B) Hub
(C) Switch (D)
3. Satellite What is the benefit of the Networking?
(A) File Sharing (B) Easier access to Resources
(C) Easier Backups (D) All of the Above
4. Which of the following transmission media has the highest bandwidth?
(A) Co axial cable (B) Fiber optic cable
(C) Twisted pair cable (D) None of these
5. Given below are two addresses.
(i) http://www.abc.com/index.htm
(ii) 182.68.9.165
Identify which one of the above is an IP address and which one is a URL?
6. What is the browser name that is developed by google?
(A) Googly google (B) Chrome
(C) Firefox (D) Titanium
7. ____ is a networking device that forwards the data packets between computer networks.
(A) Repeater (B) Hub
(C) Switch (D) Router
8. Which networking device is used to amplify a network signal when it travels a long distance in
transmission media and Due to resistance of media signal becomes weak?
(A) Router (B) Switch
(C) Repeater (D) Gateway
9. Bluetooth is an example of __________
(A) personal area network
(B) local area network
(C) virtual private network
(D) wide area network
10. Which topology is based on a central node which? act as a hub?
(A) Star topology (B) Bus topology
(C) Tree topology (D) Hybrid topology
11. What is the size of IPv4?
(A) 16 bits (B) 32 bits
(C) 64 bits (D) 128 bits
12. What is the full form of NIC?
(A) Network Interchange Card
(B) Net Interconnect Card
(C) Network Interface Card
(D) Network Interconnection Card
13. Out of the following, which is the fastest wired and wireless medium of transmission?
Infrared, coaxial cable, optical fiber, microwave, Ethernet cable
14. Name the transmission media best suitable for connecting to hilly areas.

156 | P a g e
15. Neha wants to transfer data within a city at very high speed. Write the wired transmission
medium and type of network.

Assertion & Reason Type Questions: 1x5 = 5


Directions: In the following questions, A statement of Assertion (A) is followed by a statement of
Reason (R). 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 correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
16. Assertion (A): A router is more powerful and intelligent than hub or switch.
Reason (R): It has advanced capabilities as it can analyse the data and decide the data is
packed and send it to the other network.
17. Assertion (A): A protocol means the rules that are applicable for a network.
Reason (R): Local Area Network is an example of protocol.
18. Assertion (A): The microwave transmission is a line-of-sight transmission.
Reason (R): Microwave signals travel at a higher frequency than radio waves.
19. Assertion (A): A router is more powerful and intelligent than hub or switch.
Reason (R): It has advanced capabilities as it can analyse the data and decide the data is
packed and send it to the other network.
20. Assertion (A): Bus topology is based on a central which acts as a hub.
Reason (R): Local Area Network is an example of protocol.

Case based Study Type Questions 1x5 = 5

Q. 21. Rovenza Communication International (RAC) is an online corporate training provider company
for IT related courses. The company is setting up their new campus in Kolkata. You as a network
expert have to study the physical location of various blocks and the number of computer to be
possible answer for the queries (i) to (v)raised by them.

Block To block distances (in Mtrs.)

From To Distance
Administrative Finance
60
Building Building
Administrative Faculty Studio
120
Building Building
Finance Faculty Studio
70
Building Building

157 | P a g e
Expected computer to be installed in each block

Buildings Computer

Administrative 20
Building
Finance Building 40
Faculty Studio
Building 120

I. Suggest the most appropriate block, where RCI should plan to install the server.
II. Suggest the most appropriate block to block cable layout to connect all three blocks for
efficient communication.
III. Which type of network out of the following is formed by connecting the computer of these
three blocks?
LAN
MAN
WAN
IV. Which wireless channel out of the following should opted by RCI to connect to students from
all over the world?
Infrared
Microwave
Satellite connection
V. What is the satellite connection?

Q22. ABC Pvt. Ltd. is setting up the network in the Bengaluru. There are four departments named as
Market, Finance, Legal and Sales. 1x5 = 5

I. Suggest a cable layout of connections between the Departments and specify the topology.
II. Suggest the most suitable building to place he server by giving suitable reason.
III. Suggest the placement of (i) modem (ii) hub/switch in the network.
IV. The organization is planning to link its sale counter situated in various part of the same city.
Which type of network out of LAN, WAN, MAN will be formed? Justify.
V. What is the use of modem in networking?

SECTION B
SUBJECTIVE QUESTIONS:
Q. 23. Two students in the same class sitting inside the same room have connected their laptops using
Bluetooth for working on a group presentation. What kind of network have they formed? 1
Q. 24. XYZ company is planning to connect all computers, each spread over a distance of 50 metres.
Suggest an economic cable type having high speed data transfer to connect these computers. 1

158 | P a g e
Q. 25. Rahul got an assignment in which there is a question about website. But he does not know
about it. Help him to get the information of website. 1
Q. 26. When a user browses a website, the web server sends a text file to the web browser. What is the
name of this? 1
Q.27. Rahul has to share the data among various computers of his two office branches situated in the
same city. Name the network (out of LAN, MAN, PAN and MAN) which is being formed in this process.
1
Q. 28. Give the full forms of the following ½ x 4 =2
a) HTTP
b) FTP
c) VoIP
d) SSH
Q.29. Expand the following terms: ½ x 4 =2
a) SMTP
b) XML
c) LAN
d) IPR
Q.30. Write the expanded names for the following abbreviated terms used in Networking and
Communications ½ x 4 =2
a) SMTP
b) VoIP
c) GSM
d) WLL
Q.31. Write the expanded names for the following abbreviated terms used in Networking and
Communications: ½ x 4 =2
a) MBPS
b) WAN
c) CDMA
d) WLL

Q. 32. What is Network Topology? Write different types of topologies used in networking. 2
Q. 33. Distinguish between web browser and web server. 2
Q. 34. What is the difference between a webpage and website? 2
Q. 35. Explain any 3 types of networks. 3
Q. 36. What do you understand by wired media? 3
Q. 37. Explain the following terms: 5
a) Circuit Switching
b) XML
c) TELNET
d) Packet Switching
e) Gateway

159 | P a g e
SAMPLE QUESTION PAPER (THEORY)
CLASS: XII SESSION: 2024-25
COMPUTER SCIENCE (083)

Time allowed: 3 Hours Maximum Marks: 70

General Instructions:
● This question paper contains 37 questions.
● All questions are compulsory. However, internal choices have been provided in some
questions. Attempt only one of the choices in such questions
● The paper is divided into 5 Sections- A, B, C, D and E.
● Section A consists of 21 questions (1 to 21). Each question carries 1 Mark.
● Section B consists of 7 questions (22 to 28). Each question carries 2 Marks.
● Section C consists of 3 questions (29 to 31). Each question carries 3 Marks.
● Section D consists of 4 questions (32 to 35). Each question carries 4 Marks.
● Section E consists of 2 questions (36 to 37). Each question carries 5 Marks.
● All programming questions are to be answered using Python Language only.
● In case of MCQ, text of the correct answer should also be written.

Q No. Section-A (21 x 1 = 21 Marks) Marks

1. State True or False:


A line starting with a double quote (“) is treated as a comment by the (1)
Python interpreter.
2. Identify the output of the following code
snippet: str1=”JNV”
str1=###.join(str1)
print(str1)
(1)
(A) ###JNV
(B) JNV###
(C) J###N###V
(D) #JNV#JNV#
3. Which of the following expressions evaluates to True?
(A) not(not 0)
(B) True and not “” (1)
(C) not(False or True)
(D) “False” and not(False)

4. What is the output of the expression?


board=”CBSE”
(1)
print(len(board)== len(board.split()))
(A) Error

160 | P a g e
(B) True
(C) False
(D) 4
5. What will be the output of the following code
snippet? Marks = [33,68,50,41,45] (1)
print(Marks[-5::-2])

6. What will be the output of the following


code? chars = (‘a’, ‘b’, ‘c’)
chars += (10,)
print(chars)
(1)
(A) Error
(B) False
(C) (‘a’, ‘b’, ‘c’, ‘10’)
(D) (‘a’, ‘b’, ‘c’, 10)

7. Fill in the blank with correct option to make the program display all the
country names in the dictionary- Data.
Data = {‘India’:’IN’, ‘USA’:’USD’, ‘China’:’CNY’}
print(Data.______())
(1)
(A) index
(B) keys
(C) values
(D) country
8. What will be the output of the following code?
print([1]*4)
(A) [1,1,1,1]
(1)
(B) [4]
(C) [1],[1],[1],[1]
(D) Error
9. If two tables Student and Course are having 3 and 4 attributes respectively.
What will be the degree of Cartesian product (Student X Course)?
(A) 3
(1)
(B) 4
(C) 7
(D) 12

10. Which statement about index method (called as below) is true:


List.index(x)
(A) Gives error if x is not in List
(1)
(B) Gives 0 if x is not in List
(C) Gives -1 if x is not in List
(D) Gives value of x if x is in List

161 | P a g e
11. State whether the following statement is True or False:
A syntax error does not halt the execution of the program if it falls within (1)
try block.
12. What will be the output of the following code?
Class = 10
def promote():
global Class
Class += 1
promote()
promote() (1)
print(Class)
(A) 12
(B) 10
(C) Error
(D) 11
Which SQL command can delete an attribute from an existing relation?
(A) DROP ATTRIBUTE
13. (B) DELETE ATTRIBUTE (1)
(C) DROP COLUMN
(D) REMOVE
14. Fill in the blank to complete the query?
(1)
_______ TABLE Student MODIFY Roll INT;

15. Which is the correct SQL Date data.


(A) “1984-4-28”
(B) “28-4-198 (1)
(C) “28-04-1984”
(D) “1984-04-28”
16. Number of records in a relation is also known as:
(A) Cardinality
(B) Degree (1)
(C) Instance
(D) Height
17. The T in TCP/IP stands for:
(A) Transfer
(B) Transmission (1)
(C) Transaction
(D) Text

18. A multiport repeater may be termed as a: (1)

162 | P a g e
(A) Hub
(B) Gateway
(C) Bridge
(D) Modem
19. State whether true or false:
(1)
In Circuit Switching technique, data is broken into smaller packets.
Q20 and Q21 are Assertion(A) and Reason(R) 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
20. Assertion (A): The print function by default adds a new line at the end of
the content it displays.
(1)
Reasoning (R): The print function has a default parameter sep with a
space character (“ “) as its default value.
21. Assertion (A): A database can have only one relation in it.
(1)
Reasoning (R): SQL is not case-sensitive.

Q No Section-B ( 7 x 2=14 Marks) Marks

22. Explain the difference between `break` and `continue` statements in


(2)
Python.
23. Write a Python function to check if a given number is a prime number. (2)

OR
Write a Python function to display n numbers of Fibonacci Series.
24. Give two examples (code) of each of the following: (2)
(I) Assignment operators (II) Logical operators

25. What could be the possible outputs for the following code.
import random
R = random.random()*3
(2)
F = R // 1
print(F)

163 | P a g e
26. The code provided below is intended to reverse the order of element of a
tuple. However, there are syntax and logical errors in the code. Rewrite it
after removing all errors. Underline all the corrections made.
def reverse(tup):
lis = ()
last = -(len(tup)) (2)
for e in range(-1,last+1,-1):
append.lis(tup[e])
r_tup = tuple(lis)
return tup

27. What is a composite key explain with example. (2)


OR
Differentiate between Candidate Keys and Alternate Keys.
28.
Explain :
1. Bus topology (2)
2. Star topology

Q No. Section-C ( 3 x 3 = 9 Marks) Marks

29. Write a Python function COUNTA that count all the words starting with “a” or
(3)
“A” in a text file “para.txt".
30. Write user-defined functions `PUSH_P(n)` which accepts a tuple of
integers in a parameter `n` and pushes all those integers which are
positive from the tuple `n` into a Stack named `Positive`.

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

Write function SHOW() to display all element of the stack without deleting
them. If the stack is empty, the function should display 'Empty Stack'.
31. Predict the output of the following code:
Nums =[10,15,20]
for one in Nums:
for two in range(1,one//5): (3)
print(one,two,sep=”:”,end=” ”)
print()

164 | P a g e
OR
Predict the output of the following code:
base = {"a": “apple”, "b": “banana”, "c":”cat”}
str1 = ""
for key in base.keys():
if key > “a”:
print(base[key][-1], end=”&”)

Q No. Section-D ( 4 x 4 = 16 Marks) Marks

32. Consider the table “Tour” as given below

T_Id C_Name Destination Distance Cost


51 Vipin Ayodhya 1000 12000
52 Samiksha Mathura 1150 10000
53 Arnav Puri 1460 1500
54 Bhavesh Puri 1460 1800
Note: The table contains many more records than shown here.
(4)

Write SQL commands for the following queries:

(I) To display the all the distinct Tour Destinations which are at a
distance more than 1000KM with Distance.
(II) To display the Tour table with total Cost incurred in respect of
each Tour Destination.
(III) To display the amount of most costly tour.
(IV) To remove all the records having no information of cost.
33. (I) Write a python program to create a CSV file political.csv and add
following records to it:
(a) India New Delhi Asia
(4)
(b) Nepal Kathmandu Asia
(II) What are seek() and tell() functions used for? Give example for
each.

165 | P a g e
34. Consider the following tables School and Admin and answer the following
questions.

Table: School
Code TName Subject DOJ Periods
2402 Amit English 10-10-1999 25
2403 Nitin Physics 24-12-1998 23
2404 Rakshit Chemistry 11-2-2003 23
2405 Rashmi Mathematics 25-8-2003 28
2406 Sulekha Biology 21-11-2004 20

Table: Admin
Code Gender Designation
(4)
2402 Male Vice Principal
2403 Male Exam IC
2404 Male MR IC
2405 Female CCA IC
2406 Female Principal
Give theoutput of the followingSQL Commands:
(I) SELECT TName, Designation FROM School, Admin WHERE
School.Periods > 25;
(II) SELECT COUNT(*) FROM Admin,School;
Write SQL commands:
(III) To increase the periods of all teachers by 1 who have periods less
than 25 in the table School.
(IV) (A) To display no. of Female Teachers excluding principal.

35. Consider a table, named ‘Textbook’, in ‘Library’ database, having the


structure as follows:

Local_id isbn Title Author Publisher Stock

Write the following Python program to remove all the record with zero stock. (4)

Assume the following for Python-Database connectivity:


Host: localhost
User: root
Password: alphebet

166 | P a g e
Q.No. SECTION E (2 X 5 = 10 Marks) Marks

36. (i) What are CSV files?

(ii) Write a program with two user defined functions as follows:

WriteData() – to add records of articles in in the following structure to a


binary file “Record.dat”. (5)
ID Name Type Price
(Int) (String) (String) (Float)
Search() –to display name for an ID from the binary file “Record.dat”.

37. Sarvoday ICT is an event educational organization. It is setting up its


campus in Guwahati with its head office in Delhi. The Guwahati campus
will have four blocks/buildings - Admin, Resource, Training and Finance.

Guwahati Delhi

Admin Resource Head Office

Finance Training

Block to Block distances (in Mtrs.)


From To Distance
Amin Resource 65 m (5)
Admin Training 85 m
Admin Finance 55 m
Resource Training 55 m
Resource Finance 85 m
Training Finance 65 m

Distance of Delhi Head Office from Guwahati Campus = 1300 km

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

167 | P a g e
Admin 20
Resource 38
Training 10
Finance 10
Delhi Head Office 16

(I) Suggest the most appropriate location of the server inside the
Guwahati campus. Justify your choice.
(II) Which hardware device will you suggest to connect all the
computers within each building?
(III) Draw the cable layout to efficiently connect various buildings within
the Guwahati campus. Which cable would you suggest for the
balanced data transfer rate and cost for the network?
(IV) What type of network (PAN, LAN, MAN, or WAN) will be set up
among the computers connected in the Guwahati campus?
(V) What would be the best suitable media to connect Guwahati
campus to the head office in Delhi for reliable and high speed
connectivity?

168 | P a g e
MARKING SCHEME
Class: XII Session: 2024-25
Computer Science (083)

Time allowed: 3 Hours Maximum Marks: 70


Q No. SECTION A (21X1=21) Marks

1. False (1)
(1 mark for correct answer)

2. (C) J###N###V (1)


(1 mark for correct answer)

3. (A) not (not 0) (1)


(1 mark for correct answer)

4. (C) False (1)


(1 mark for correct answer)

5. 33 (1)
(1 mark for correct answer)

6. (D) (‘a’, ‘b’, ‘c’, 10) (1)


(1 mark for correct answer)

7. (B) keys() (1)


(1 mark for correct answer)

8. (A) [1,1,1,1] (1)


(1 mark for correct answer)

9. (D) 12 (1)
(1 mark for correct answer)

10. (A) Gives error if x is not in List (1)


(1 mark for correct answer)

11. True (1)


(1 mark for correct answer)

12. (A) 12 (1)


(1 mark for correct answer)

13. (C) DROP COLUMN (1)


(1 mark for correct answer)

169 | P a g e
14. ALTER (1)
(1 mark for correct answer)

15. (D) 1984-04-28” (1)


(1 mark for correct answer)

16. (A) Cardinality (1)


(1 mark for correct answer)

17. (B) Transmission (1)


(1 mark for correct answer)

18. (A) Hub (1)


(1 mark for correct answer)

19. False (1)


(1 mark for correct answer)

20. (B) Both A and R are true and R is not the correct explanation for A. (1)
(1 mark for correct answer)

21. (D) A is False but R is True (1)


(1 mark for correct answer)

Q No. SECTION B (7 X 2 =14) Marks

22. A break statement, (which is usually put under some conditional block within (2)
a loop) if executed takes the sequence of execution out of the immediate
parent loop.
A continue statement, (which is also usually put under some conditional
block within a loop) if executed takes the sequence of execution to the next
iteration of the immediate parent loop disregarding the remaining
statements in the current iteration.
(1(x2 = 2) mark for each correct explanation)
23. num = 11 (2)
if num > 1:
for i in range(2, (num//2)+1):
if (num % i) == 0:
print(num, "is not a
prime number")
break
else:
print(num, "is a prime
number")

170 | P a g e
else:
print(num, "is not a prime
number")
2 Marks for the correct code

OR
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
print(next_number, end=" ")
count += 1
num1, num2 = num2,
next_number
next_number = num1 + num2
print()
2 Marks for the correct code
24. (I) any two of: =, +=, -=, *=, /=, //=,%= (2)

½ x 2 = 1 marks
(II) Any two of: and, or, not

½ x 2 = 1 marks

25. (2)
0.0, 1.0, 2.0, 3.0
½ x 4 = 2 Mark)

26. def reverse(tup): (2)


lis = [] ### or list()
last = -(len(tup))
for e in range(-1,last-1,-1):
append.lis(tup[e])
r_tup = tuple(lis)
return r_tup

(½ mark each for correcting 4 mistakes)

171 | P a g e
27. (When any of the attributes alone is not eligible to become a primary key, a (2)
set of more than one attributes is used for the same. The key thus created
is termed as a composite key.

(1 mark for correct explanation )


(1 mark for example )
OR
All those attribute or set of attributes which are eligible to become a
primary key are termed as candidate keys. When one among those is
selected as Primary key the rest are referred to as Alternate Keys.

(2 mark for correct differentiation )


28. 1. Bus topology: In a bus topology there lies a high bandwidth wire(called (2)
backbone wire) an all the nodes of the network are connected through it.
(1 mark for correct explanation)

2. Star topology: There lies a central node (a hub/switch etc.) through


which all the other nodes are connected.
(1 mark for correct explanation)

Q No. SECTION C (3 X 3 = 9) Marks

29. def COUNTA(): (3)

count = 0
f=open("para.txt",'r')
content=f.read()
words=data.split()
for word in words:
if word[0] == “a” or word[0] == “A”
count += 1
f.close()
return count
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
(½ mark for splitting the text into words)
(1 mark for correctly counting the desired words)

172 | P a g e
30 (I) (3)
def PUSH_P(n):
for i in n:
if i > 0:
Positive.append(new_book)
(II)
def POPIT():
if not Positive:
print("Underflow")
else:
return(Positive.pop())
(III)
def SHOW():
if not Positive:
print("Empty Stack")
else:
for I in Positive:
print(i)
(3x1 mark for correct function body; No marks for any function header as it
was a part of the question)

31. 10:1 (3)


15:1 15:2
20:1 20:2 20:3

OR

a&t

(1 mark for correct output in each iteration)


(deduct ½ mark for not printing @/#)

Q No. SECTION D (4 X 4 = 16) Marks

32 (I) SELECT DISTINCT(Destination) FROM Tour WHERE Distance > 1000; (4)
(II)SELECT SUM(Cost) FROM Tour GROUP BY Destination;
(III)SELECT MAX(Cost) FROM Tour;
(IV)DELETE FROM Tour WHERE Cost is null;
(4 x 1 mark for each correct query)

173 | P a g e
33 (I) (4)
import csv
f = open(“political.csv”, “a”)
csv_w = csv.writer(f)
csv_w.writerow([“India”, “New Delhi”, “Asia”])
csv_w.writerow([“Nepal”, “Kathmandu”, “Asia”])
f.close()
(II) seek function is used to move the file offset at desired position in a file
object. Whereas tell function is used to get the position of file offset.
34 (I) (4)
TName Designation
Rashmi CCA IC

(II) 5

(III) UPDATE School SET Periods = Periods+1 WHERE Periods < 25;
(IV) SELECT COUNT(*) FROM Admin WHERE Gender = Female AND
Designation != Principal;
35 import mysql.connector as mycon (4)
mydb=mycon.connect(host="localhost", user="root", passwd="alphabet",
. database="Library")
mycur=mydb.cursor()
query = “delete from Textbook where stock = 0”
mycur.execute(query)
36 (I) CSV file are text file that follow a structure of saving values separated by (5)
commas. Comma Separated Value.

(II)
def WriteData():
ID = int(input(“Enter ID”))
Name = input(“Enter Name”)
Type = input(“Enter Type”)
ID = float(input(“Enter Price”))
D = {“ID”:ID, “Name”: Name, “Type”:Type, “Price”:Price}
import pickle
f = open(“Record.dat”, “ab”)
pickle.dump(D, f)
f.close()

174 | P a g e
(III)
def Search(id):
import pickle
f = open(“Record.dat”, “ab”)
try:
while True:
rf = pickle.load(f)
if rf[ID] == id:
print(rf[“Name”])
break
except:
print(“End of file”)

37 (I) Resource block as it has the maximum number of Computers.


(II) Switches
(III)
Guwahati

Admin Resource

Finance Training

UTP cable(Ethernet Cable)

(IV) LAN
(V) Optic Fibre

175 | P a g e

NAVODAYA VIDYALAYA SAMITI 
 
SHILLONG REGION 
 
SADHANA PROGRAM 
(2024-25) 
 
 
 
PRACTICE PAPERS 
 
For 
 
CLASS XII 
 
SUBJ
2 | P a g e
3 | P a g e  
 
Development Committee 
 
 
S. No. 
 
NAME DESIGNATION & JNV OF THE 
RESOURCE PERSON 
 
ROLE 
 
 
1 
 
SH. ABD
4 | P a g e  
 
 
 
CONTENTS:- 
 
 
 
 
 
 
 
 
 
 
 
 
 
S.NO. 
PARTICULERS 
PAGE NO. 
1 
Practice Paper Set No. 1 
5-19 
2
5 | P a g e  
 
 
 
PRACTICE QUESTION PAPER (THEORY) 
CLASS: XII SESSION: 2024-25 COMPUTER 
SCIENCE (083) 
 
Time allowed: 3
6 | P a g e  
 
4. 
In Python, ………….. defines a block of statements. 
a) Block 
b) loop 
c) indentation 
d) { } 
 
 
 
(1) 
5
7 | P a g e  
 
10. 
State whether the following statement is True or False: 
          In a try-except block, if an exceptio
8 | P a g e  
 
15. 
Consider the following statement: 
SELECT * FROM product ORDER BY rate _______, item_name _______ ; 
Whi
9 | P a g e  
 
21. 
Assertion (A): The HAVING clause is used with aggregate functions. 
Reasoning (R): WHERE clause places c
10 | P a g e  
 
25. 
What possible output(s) are expected to be displayed on the screen at the time of 
execution of the pro

You might also like