Grade 12
Grade 12
SECTION – A (21x1=21)
1. State True or False:
While handling exception in Python, name of the exception has to be compulsorily
added with except clause. False
2. Consider the following Python statement:
F = open (‘CONTENT.TXT’)
Which of the following is an invalid statement in Python?
a) F.seek (1, 0) b) F.seek (0, 1) c) F.seek (0, -1) d) F.seek (0, 2)
3. Which of the following statements is false?
a) A try-except block can have more than one except statement
b) One block of except statement cannot handle multiple exceptions.
c) The finally block is always executed
d) When 1 = = “1” is executed, no exception is raised 1
4. Which pickle module is used to write a Python object to a binary file?
a) save () b) serialize () c) store () d) dump ()
5. Which of the following file opening mode in Python, generates an error if the file does not
exist?
a) a b) r c) w d) w+
6. The correct syntax of seek () is:
a) file_obkect.seek (offset [, reference_point])
b) seek (offset [, reference_point])
c) seek (offset, file_object)
d) seek.file_object (offset)
7. State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct. True
8. Which of the following functions changes the position of the file pointer and return its new
position?
a) flush () b) tell () c) seek () d) offset ()
9. Which of the following is a function / method of the pickle module?
a) reader () b) writer () c) load () d) read ()
10. Which of the following option is the correct Python statement to read and display the first
10 characters of a text file “Notes.txt”?
a) F = open (‘Notes.txt’); print (F.load (10))
b) F = open (‘Notes.txt’); print (F.dump (10))
c) F = open (‘Notes.txt’); print (F.read (10))
d) F = open (‘Notes.txt’); print (F.write (10))
11. A text file opened using the following statement:
MyFile = open (‘Notes.txt’)
Which of the following is the correct Python statement to close it?
a) MyFile = close (‘Notes.txt’)
b) MyFile = close (‘Notes.txt’)
c) Close.MyFile ()
d) MyFile.close ()
12. Which of the following option is the correct usage for the tell () of a file object?
a) It places the file pointer at a desired offset in a file.
b) It returns the entire content of a file
c) It returns the byte position of the file pointer as an integer
d) It tells the details about the file.
13. Which of the following is the correct expansion of csv?
a) Comma Separated Values
b) Centrally Secured Values
c) Computerised Secured Values
d) Comma Secured Values
14. Suppose the content of a text file Notes.txt is:
“The way to get started is to quit talking and begin doing”
What will be the output of the following Python code?
F = open (“Notes.txt”)
F.seek (29)
S = F.read ()
print (S)
a) The way to get started is to
b) quit talking and begin doing
c) The way to get started is to quit talking and begin doing
d) gniodnigebdnagniklattiuqotasidetrats teg ot yaw ehT
15. Which of the following Python modules is imported to store and retrieve objections using
the process of serialization and de-serialization?
a) csv b) binary c) math d) pickle
16. Which of the following function is used with the csv modules in Python to read the
content of a csv file into an object?
a) readrow () b) readrows () c) reader () d) load ()
17. Suppose the content of “Rhymes.txt” is:
Baa baa black sheep,
have you any wool?
What will be the output of the following Python code?
F = open (“Rhymes.txt”)
S = F.read ()
L = S.split ()
for i in L:
if len(i) % 3!= 0:
print (i, end=” “)
a) Baa baa you any b) black have wool?
c) black sheep, have wool? d) Error
18. Stdout, stdin and stderr are _____________
a) Structure b) File pointer c) File description d) Streams
19. Text files store information in _____________ characters.
a) ASCII b) Unicode c) (a) and (b) d) None of theseIn
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 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 (or partly true).
d) A is false (or partly true) but R is true.
e) Both A and R are false or not fully true.
20. Assertion (A): CSV file is a human readable text file where each line has a number of
fields, separated by comma or some other delimiter.
Reason (R): writerow () method is used to write a single row in a CSV file. (b)
21. Assertion (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reason (R): Binary files are just like normal text files and can be read using a text editor
like Notepad. (c)
SECTION – B (7x2=14)
22. Write a function in Python to read a text file, Alpha.txt and displays those lines which
begin with the word ‘You’.
def test ():
f1 = open (“Alpha.txt”, “r”)
data = f1.readlines ()
for line in data:
L = line.split ()
if L [0] = = “You”:”
print (line)
f1.close ()
23.a) Write a statement in Python to perform the following operations:
i) To open a text file “MYPET.TXT” in write mode.
f1 = open (“MYPET.TXT”, ‘w’)
ii) To open a text file “MYPET.TXT” in read mode.
f2 = open (“MYPET.TXT”, ‘r’)
b) Observe the following code and answer the question that follow:
File = open (“Mydata”, “a”)
________________ #Blank 1
File.close ()
i) What type (Text/Binary) of file is Mydata?Text file
ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”.
File.write(“ABC”)
24. How is method write () different from writelines () in python?
write (str) writes a string into a file while writelines (sequence) writes a list of strings to the file.
Ex: str = “Hello”
f.write (str)
strlist = [“I” , “love”, “Python”]
f.writeline (list)
25. i) Write a statement in Python to open a text file WRITEUP.TXT so that new content can
be written in it.
i) file = open (“WRITEUP.TXT”, “w”)
(OR)
file = open (“WRITEUP.TXT”, “w+”)
ii) Nancy intends to position the file pointer to the beginning of a text file. Write Python
statement for the same assuming F is the File object.
F.seek (0)
26. Write a method in Python to read lines from a text file DIARY.TXT, and display those
lines, which are starting with the letter ‘P’.
def countP ():
fname = “DIARY.TXT”
with open (fname, ‘r’) as f:
l = f.readlines ()
for line in l:
if l.strip = = ‘p’:
print (line)
f.close ()
27. Differentiate between a Text file and a Binary File.
Text File Binary File
A text file is a file that stores information in A binary file is a file that stores in the form
the form of a stream of ASCII or Unicode of a stream of bytes.
characters.
In text files, each line of text is terminated In a binary file, there is no delimiter for a
with a special character known as EOL (End line and no character translations occur
of Line) character. here.
28. i) What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter
whether or not an exception is thrown or caught.
ii) What are the advantages of exception handling?
- Exception handling separates error handling code from normal code.
- It clarifies the code and enhances readability
- It stimulates consequences as the error-handling takes place at one place and in
one manner.
- It makes for clear, robust, fault-tolerant programs.
(OR)
i) Identify the type of exception for the codes and inputs given below:
a) #input as “K”
x = int (input (“Please enter a number:”))
Value error
b) x = 8
print (x)
Name error
c) mylist = [2, 3, 4]
print (mylist [4])
Index error
d) for a in range (0, 9):
print (20/a)
Zero Division Error
ii) Give two examples of Exceptions.
- Divide by zero error
- Accessing the elements of an array beyond its range.
- Invalid input
- Hard disk crash
- Opening a non-existent file
- Heap memory exhausted. (any two)
SECTION – C (3x3=9)
29. Write a function, vowelCount () in Python that counts and displays the number of vowels
in the text file named Poem.txt.
def vowel Count ():
f = open (“Alpha.txt”, ‘r’)
data = str (f.read ())
cnt = 0
for ch in data:
in ch in “aeiouAEIOU”:
cnt = cnt + 1
print (cnt)
f,close ()
30. Write a function count_Dwords () in Python to count the words ending with a digit in a
text file “Details.txt”.
Example:
If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be:
Number of words ending with a digit are 4.
def count_words ():
f = open (“Details.txt”, “r”)
lst = f.readlines ()
wrd = “”
count = 0
for ln in lst:
Line = ln.split (‘ ‘)
for wrd in Line:
if wrd [-1] >= ‘0’ and wrd [-1] <= ‘9’:
count + = 1
wrd = “ “
print (“No. of words ending with a digit is:”, count)
f.close ()
31. Write a function ETCount () in Python, which should read each character of a text file
“TESTFILE.TXT” and then count and display the count of occurrence of alphabets E and T
individually (including small cases e and t too).
Example:
If the file content is as follows:
Today is a pleasant day.
It might rain today.
It is mentioned on weather sites.
The ETCount () function should display the output as:
E or e: 6
T or t: 9
def ETCount() :
file = open ('TESTFILE.TXT', 'r')
lines = file.readlines()
countE=0 countT=0
for w in lines :
for ch in w:
if ch in 'Ee':
countE = countE + 1
if ch in 'Tt':
countT=countT + 1
print ("The number of E or e : ", countE)
print ("The number of T or t : ", countT)
file.close()
SECTION – D (4x4=16)
32. Sangeetha is a Python programmer working in a computer hardware company. She has to
maintain the records of the peripheral devices. She created a csv file named Peripheral.csv, to
store the details.
The structure of Peripheral.csv is:
[P_id, P_name, Price]
Where
P_id is Peripheral device ID (integer)
P_name is Peripheral device name (String)
Price is Peripheral device price (integer)
Sangeetha wants to write the following user defined functions:
Add_Device (): to accept a record from the user and add it to a csv file, Peripheral.csv
Count_Device (): To count and display number of peripheral devices whose price is less than
1000.
import csv
def Add_Device ():
csvfile = open (“Peripheral.csv”, ‘a’)
cwriter = csv.writer (csv file)
P_id = int (input (“Input device id:”))
P_name = input (“Input device name:”)
P_Price = int (input (“Input device price:”))
devdata = [P_id, P_name, P_price]
cwriter.writerow (devdata)
csv.close ()
def Count_Device ():
c=0
csvfile = open (“ Peripheral.csv”, ‘r’)
creader = csv.reader (csvfile)
for rec in creader:
if int (rec[2]) < 1000:
c+ = 1
print (“Devices with price less than 1000:”, c)
csvfile.close ()
33. Consider a binary file ‘INVENTORY.DAT’ that stores information about products using
tuple with the structure (Product ID, ProductName, Quantity, Price). Write a Python function
expensiveProducts () to read the contents of ‘INVENTORY.DAT’ and display details of
products with a price higher than Rs. 1000. Additionally, calculate and display the total count
of such expensive products.
For example: If the file stores the following data in binary format
(1, ‘ABC’, 100, 5000)
(2, ‘DEF’, 250, 1000)
(3, ‘GHI’, 300, 2000)
Then the function should display
Product ID: 1
Product ID: 3
Total expensive products: 2
import pickle
def expensiveProducts ():
with open (‘INVENTORY.DAT”, ‘rb’) as file:
expensive_count = 0
while True:
try:
product_data = pickle.load (file)
product_id, product_name, quantity, price = product_data
if price > 1000:
print (“ProductID:”, product_id)
expensive_count + = 1
except EOFError:
break
print (“Total expensive products:”, expensive_count)
expensiveProducts ()
34. i) What is the advantage of using a csv file for permanent storage?
ii) Write a program in Python that defines and calls the following user defined functions:
a) ADD () – To accept and add data of an employee to a CSV file ‘record.csv’. Each
record contains of a list with field elements as empid, name and mobile to store employee id,
employee name and employee salary respectively.
b) COUNTR () – To count the number of records present in the CSV file named
‘record.csv’.
i) Advantage of using csv files:
- It is a type of text file and is human readable.
- it can be opened in spreadsheets like Excel and in text editors too.
ii) import csv
def ADD ():
fout = open (“record.csv”, ‘a’, new line =”\n”)
wr = csv.writer (fout)
empid = int (input (“Enter Employee id::”))
name = input (“Enter name::”)
mobile = int (input (“Enter mobile number::”))
lst = [empid, name, mobile]
wr.writerow(lst)
fout.close ()
def COUNTR ():
fin = open (“record.csv”, ‘r’, new line = “\n”)
data = csv.reader (fin)
d = list (data)
print (len (d))
fin.close ()
ADD ()
COUNTR ()
35. Aman is a Python programmer. He has written a code and created a binary file record.dat
with employeeid, ename and salary. The file contains 10 records. He now has to update a
record based on the employee id entered by the user and update the salary. The updated
record is then to be written in the file temp.dat. The records which are not to be updated also
have to be written to the file temp.dat. If the employee id is not found, an appropriate
message should to be displayed. As a Python expert, help him to complete the following code
based on the requirement given above:
import _______ #Statement 1
def update_data():
rec={} fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their 14 salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
pickle
(ii) Write the correct statement required to open a temporary file named temp.dat. (Statement
2)
fout = open (‘temp.dat’, ‘wb’)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file,
record.dat and in Statement 4 to write the updated data in the file, temp.dat?
Statement 3: pickle.load (fin)
Statement 4: pickle.dump (rec, fout)
SECTION – E (2x5=10)
36. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he
has created a csv file named Result.csv, to store the results of students in different sports
events. The structure of Result.csv is:
[St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie' For efficiently
maintaining data of the event, Vedansh wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column
headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
def Accept ():
sid = int (input (“Enter Student ID”))
sname = input (“Enter Student Name”)
game = input (“Enter name of game”)
res = input (“Enter Result”)
headings = [“Student ID”, “Student Name”, “Game Name”, “Result”]
data = [sid, sname, game, res]
f = open (“Result.csv”, ‘a’, newline=’ ‘)
csvwriter = csv.writer (f)
cswriter.writerow (headings)
csvwriter.writerow (data)
f.close ()
def wonCount ():
f = open (“Result.csv”, ‘r’)
csvreader = csv.reader (f, delimiter=’,’)
head = list (csvreader)
print (head [0])
for x in head:
if x [3] = = “WON”:
print (x)
f.close ()
37. i) A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype as parameter and
displays all the records from the binary file CINEMA.DAT, that have the value of Movie
Type as mtype.
def Search type (mtype):
f = open (“CINEMA.DAT”, ‘rb’)
try:
while True:
data = pickle.load (f)
if data [2] = = mtype:
print (“Movie Number:”, data [0])
print (“Movie Name:”, data [1])
print (“Movie Type:”, data [2])
except EOFError ():
f.close ()
ii) Differentiate between r+ and w+ file modes in Python.
r +:
- Opens a file for both reading and writing.
- The file pointer will be at the beginning of the file.
w +:
- Opens a file for reading as well as writing.
- Overwrites the file if it is already exists and creates a new file if it doesn’t exist.