Revision 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Montfort Senior Secondary School

Sundaranadappu, Sivagangai
Computer Science (083)
Second Revision Examination - 2023
Class: XII Max Marks: 70
Roll No: Time: 3 hrs.

General Instructions:
• Please check this question paper contains 35 questions.
• The paper is divided into 4 Sections- A, B, C, D and E.
• Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
• Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
• Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
• Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
• Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
• All programming questions are to be answered using Python Language only.
__________________________________________________________________________________
1. To read the content of the file as a string via a file object “f”.
a) F.read(2) b) f.read() c) f=file.readline() d) f.readlines()
2. Which type of file does not have delimiters? Binary files
Delimiters are characters or symbol used to separate values, keywords or
identifiers in code.type of delimiters in python.
Special characters, .(dot), ()(parentheses), [] (square brackets), {}(curly
brackets, ;(semicolon, :(colon), ,(comma), ->(arrow)
Operators: Arthmetic operators, comparision, logical and assignment.
White space: space(), Tab(\t), line break(\n), carriage return(\r)
3. Ranjani is working on the sports.dat file but she is confused about how to read
data from the binary file. Suggest a suitable line for her to fulfil her wish.
Import pickle
Def sports_read():
F1=open(“sports.dat”,”rb”)
________________________
Print (data)
F1.close()
Sports_read()
Ans: data=f1.load (f).
4. What will be the output of the following code:
d1={1:2,3:4,5:6}
d2=d1.popitem()
Print(d2)
a) {1:2} b) {5:6} c) (1,2) d) 5,6)
5. Consider the Python statement:f.seek(10,1)
Choose the correct statement from the following:
a) File pointer will move 10 byte in forward direction from beginning of the file.
b) File pointer will move 10 byte in forward direction from end of the file
c) File pointer will move 10 byte in forward direction from current location
d) File pointer will move 10 byte in backward direction from current location
f.seek(10,1): in python f.seek() is a file object method that changes the
current file position.
Syntax: f.seek(offset,whence)
Arguments:
Offset: number of bytes to move from the specified position
Whence: reference position(default is 0, beginning of the file)
Whence values:
0 (or os.SEEK_SET): begininig of the file.
1 (or os.SEEK_CUR): Current position
2 (or os.SEEK_END): end of the file.
f.seek(10,1)
offset: 10 bytes.
Whence: 1 current position
6. State True or False
“ If a loop terminates using break statement, loop else will not execute” TRUE
7. Consider a list L = [5, 10, 15, 20], which of the following will result in an error.
a) L[0]+=3 b) L+=3 c) L*=3 d) L[1]=45
Ans: L+=3 attempts to add an integer(3) to a list(L), which is not supported
and results in a TypeError.
Other options:
a) L[0] +=3 increments the first element by 3 resulting[8,10,15,20] valid.
b) L*=3 creates a new list with the orginal elementsrepeated three times.
[5,10,15,20, 5, 10, 15, 20, 5, 10,15, 20]. Valid
c) L[1]=45 replaces the second element(1) with 45: [5, 45, 15, 20]
8. Which of the following is not true about dictionary?
a) More than one key is not allowed b) Keys must be immutable
b) Values must be immutable d) when duplicate Keys encountered,
the last assignment wins
9. Which of the following statements 1 to 4 will give the same output?
tup =(1,2,3,4,5)
print (tup[:-1]) #Statement 1
print (tup[0:5]) #Statement 2
print (tup[0:4]) #statement 3
print(tup[-4:]) #statement 4
a) Statement 1 and 2 b) Statement 2 and 4 c) Statement 2 and 5 d)
Statement 1 and 3
10. What possible output(s) will be obtained when the following code is executed?
Import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN=random.randint(1,3)
LAST = randome.randint(BEGIN,4)
for x in range(BEGIN, LAST +1):
Print(VALUES[x],end=”_”
a) 30-40-50- b) 10-20-30-40- c) 30-40-50-60- d) 30-40-50-60-80-
11. Which of the following command is used to move the file pointer 2 bytes ahead
from the current position in the file stream named fp?
a) fp.seek(2,1) b) fp.seek(-2,0) c) fp.seek(-2,-2) d) fp.seek(2,-2)
12. Predict the output of the following code:
Def ChangeList(M,N):
M[0] = 100
N = [2,3]
L1 = [-1, -2]
L2 = [10, 20]
Change Lists(L1,L2)
Print(L1[0],”#”,L2[0])
a) -1 # 10 b) 100 # 10 c) 100 # 2 d) -1 # 2
13. Which of the following is not a function of csv module?
a) Readline() b) writerow() d) reader() d) writer()
14. Which of the following statement is incorrect?
a) A file handle is a reference to a file on disk b) File handle is used to read and
write data to a file on disk c) All the functions that you perform on a disk file
can’t be performed through file handle d) None of these.
15. What will be the output of the following code in python?
S=”ComputerExam”
Print(S[2]+S[-4]+S[1:-7])
a) mEomput b) mEompu c) MCompu d) mEerExam
16. which of the following(s) is/are valid identifiers in Python?
a) For b) elif c) _123 d) None
17. Assertion (A): Text file stores information in ASCII or UNICODE characters.
Reasoning (R): In text file there is no delimiter (EOL) for line. (End of Line)

a) A is True but R is False


18. Asserestion (A): Access mode ‘a’ opens a file for appending content at the end of the
file.
Reason (R): The file pointer is at the end of the file if the file exists and opens in
write mode. Both A and R are true and R is the correct explanation for A

SECTION B

19. Rewrite the following code in python after removing all syntax error(s) and
underline each correction made by you in the code:
D = dict[]
C=1
While c<5:
K = input(“Name:”)
V = int(input(“Age:”)
D(k) = v
Print(popitem))
Foe a,b in D.item:
Print(a,b)
Ans: D=dict{} or D=dict()
Count=0 or i=1
V = int(input(“Age:”))
D[K] = v in python dictionary assignments uses a square brackets[] not
parentheses().
Print(D.popitem())
For a,b in D.item: should be for a,b in D.items():
D=dict()
count = 0
while count <5:
K= input(“Name:”)
V = int (input(“Age:”)
D[K]=V
Count +=1
Print(D.popitem())
For a,b in D.items():
Print(a,b)
20. Write the output of the following code:
L1= [100,900,300,400,500]
START=1
SUM=0
for C in range (START,4):
SUM=SUM+L1[C]
Print (C,”:”,SUM)
SUM=SUM+L1[0]*10
Print (SUM)
Ans: C=1, SUM =900+100*10=1900
C=2, SUM = 1900+300+100*10=2800
C=3 Sum= 2800+400+100*10=3700
21. What is the difference between r and rb mode in python?

Ans: r is used to rea text files and rb is used to read binary file.

22. What is EOFError? How can handle EOFError in python?


Ans: EOFError is raised when one of the built-in function input() or
raw_input() hits an end-of-file condition (EOF) without reading any data. We
can overcome this issue by using try and except keywords in python, called
Exception Handling.
23. Predict the output for the following python snippet
def calc(p,Q=3):
ans=1
for x in range(q):
ans=ans*p
return ans
power = calc(3)
print(power,’9’)
power=calc(3,2)
print(power,’27’)
Ans: 27 9
9 27
24. Write the python statement for each of the following tasks using BUILT- IN
functions/methods only:
i) To insert an element 200 at the third position, in the list L1.
ii) To check whether a string named, message ends with a full stop/ period or
not.
Ans:
i) L1.insert(2,200)
ii) Message.endswith(‘.’)

Explanation: the insert () function inserts an element at the index


specified.

The endswith() function checks weather a string ends with a specific


string or not and returns True/False.

25. Rewrite the following code in Python after removing all syntax errors:
Underline each correction done in the code:
Runs = (10, 5,0,2,4,3)
For I in runs:
If I=0:
Print(Maiden Over)
Else
Print(Not Maiden
Ans:
Runs = ( 10, 5, 0, 2, 4, 3)
For i in Runs:
If I==0:
Print(“Maiden Over”)
Else:
Print(“Not Maiden”)
SECTION – C
26. Write the Python program to count number of words in a given string that start
with vowels.
27. Predict the output of the python code given below:
def calculate(str):
text=”
x=range(len(str)-1)
for I in x:
if str[i].isupper():
text+=str[i]
elif str[i].islower():
text+=str[i+1]
else:
text+=’@’
return text
start=’Pre-board exam’
final=calculate(start)
print(final)

The output of the given code will be:


Preeboard@xam
Here's how it works:

1. The function calculate(str) iterates over the input string start = 'Pre-board exam'.
2. For each character:
• If the character is uppercase (str[i].isupper()), it appends the character itself to text.
• If the character is lowercase (str[i].islower()), it appends the next character (str[i+1]) to text.
• Otherwise (for non-alphabet characters like spaces, hyphens, etc.), it appends '@' to text.
3. The loop runs until the second last character (range(len(str)-1)), so the last character is not
processed.

Here's the step-by-step breakdown:

Index (i) Character Action text

0 P Append 'P' (uppercase) P

1 r Append 'e' (next char) Pe

2 e Append 'e' (next char) Pee

3 - Append '@' Pee@

4 b Append 'o' (next char) Pee@o

5 o Append 'a' (next char) Pee@oa

6 a Append 'r' (next char) Pee@oar

7 r Append 'd' (next char) Pee@oard

8 d Append ' ' (next char) Pee@oard

9 (space) Append '@' Pee@oard@

10 e Append 'x' (next char) Pee@oard@x

11 x Append 'a' (next char) Pee@oard@xa

12 a Append 'm' (next char) Pee@oard@xam

m (Not processed, last char)

The final output is Preeboard@xam. Pee-o@xam


28. What role is played by files modes in file operations? Describe the various file
mode constants and their meanings:
File Mode Description Purpose
“r” Read only Open file in read only
mode
“w” Write only Opens the file in write
mode.
“a” Append
“r+ Read and write
“w+” Write and read
“a+” Write and read
29. What are the advantages of saving data in Binary form and Text form?

ANS: Advantages of Saving Data in Binary Form:

1. Faster Read/Write: Binary data is read and written more quickly than text data.
2. Space Efficiency: Binary data occupies less storage space than text data.
3. Improved Security: Binary data is more difficult to interpret and modify without authorization.
4. Better Performance: Binary data is ideal for large datasets, graphics, and multimedia files.
5. Platform Independence: Binary data remains consistent across different platforms.

Advantages of Saving Data in Text Form:

1. Human Readability: Text data is easily readable and understandable by humans.


2. Platform Compatibility: Text data can be easily transferred between different platforms.
3. Editing Flexibility: Text data can be easily edited using text editors.
4. Error Detection: Errors in text data are easier to detect and correct.
5. Simple Data Exchange: Text data is ideal for simple data exchange between applications.

When to Use Each:

1. Binary Form:
• Large datasets
• Graphics and multimedia files
• High-performance applications
• Secure data storage
2. Text Form:
• Configuration files
• Simple data exchange
• Human-readable data
• Editing and debugging purposes

Common File Extensions:

1. Binary Form: .exe, .bin, .jpg, .mp3


2. Text Form: .txt, .csv, .json, .xml

In summary, binary form is ideal for efficient storage and performance, while text form is suitable for
human readability, platform compatibility, and simple data exchange. The choice between binary and
text form depends on the specific requirements of your application or use case.

30. What is the difference between a Local Scope and Global Scope? Also, give
a suitable Python code to illustrate both.

Ans: A local scope is variable defined within a function. Such variables are
said to have local scope. With example
A global variable is a variable defined in the ;main’ program (_main_
section). Such variables are said to have global scope. With example
OR
Python supports three types of formal arguments :
1) Positional arguments (Required arguments) - When the function call
statement must match the number and order of arguments as defined in
the function definition. Eg. def check (x, y, z) :
2) Default arguments – A parameter having default value in the function
header is known as default parameter. Eg. def interest(P, T, R=0.10) :
3) Keyword (or named) arguments- The named arguments with assigned
value being passed in the function call statement. Eg. interest (P=1000,
R=10.0, T = 5)
SECTION D
31. Ashok Kumar of class 12 is writing a program to create a CSV file
“empdata.csv” with empid, name and mobile no and search empid and
display the record. He has written the following code. As a programmer, help
him to successfully execute the given task.
import _____ #Line1
fields=['empid','name','mobile_no']
rows=[['101','Rohit','8982345659'],['102','Shaurya','8974564589'],
['103','Deep','8753695421'],['104','Prerna','9889984567'],
['105','Lakshya','7698459876']]
filename="empdata.csv"
with open(filename,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.___________ #Line2
csv_w.___________ #Line3
with open(filename,'r') as f:
csv_r=______________(f,delimiter=',') #Line4
ans='y'
while ans=='y':
found=False
emplid=(input("Enter employee id to search="))
for row in csv_r:
if len(row)!=0:
if _____==emplid: #Line5
print("Name : ",row[1])
print("Mobile No : ",row[2])
found=True
break
if not found:
print("Employee id not found")
ans=input("Do you want to search more? (y)")

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


(b) Write a code to write the fields (column heading) once from fields list
in Line2.

(c) Write a code to write the rows all at once from rows list in Line3.
(d) Fill in the blank in Line4 to read the data from a csv file.
(e) Fill in the blank to match the employee id entered by the user with the
empid of record from a file in Line5.
Ans:
a) csv
b) writerow(fields)
c) writerows(rows)
d) csv.reader
e) row[0]
32. i) what is the difference between ‘r’ and ‘rb’ mode in python file?

32. i). How csv files are different from normal text files?

Ans: CSV and TXT files store information in plain text. The first row in the file defines the names for
all subsequent fields. In CSV files, fields are always separated by commas. In TXT files, fields can be
separated with a comma, semicolon, or tab.

ii. write a syntax to create a reader object and write object to read and write the content of a
CSVfile.

Syntax to create reader object:


Object=csv.reader(“filehandle”)
Object=csv.writer(“filehandle”)
SECTION E
33. I) What is Pickling or Serialization?
The process of converting Python object hierarchy into byte stream so that it can be written into a file.

ii)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.

Def countrec():

Num=0

Fobj=open(“salary.dat”,’rb’)

Try:

While true:

rec=pickle.load(fob)

if rec[2]>20000:

Print(rec[0],rec[1],rec[2])

except:

fobj.close()

34. write a program in python that defines and calls the following user defined functions:
i) INSERT()- to accept and add data of a Student to a CSV file ‘Sdetails.csv’, each record
consists of a list with field elements as RollNo, Class and Marks to store roll Number of
students, name of student, class and marks obtained by the student.

import csv #( ½ mark for import csv)


def INSERT(): #(1 ½ for correct definition of function)
fh=open("Sdetails.csv",'w')
swriter=csv.writer(fh)
ans='y'
swriter.writerow(['RollNo','Name','Class','Marks'])
ans='y'
while ans=='y' or ans=='Y':
rn=int(input("Enter Roll No"))
nm=input("Enter Name")
cl=int(input("Enter class"))
mk=int(input("Enter marks"))

srec=[rn,nm,cl,mk]
swriter.writerow(srec)
ans=input("if you want to enter more record press Y/N")
fh.close()

COUNTROW() – to count the number of records present In the CSV file named
‘Sdetails.csv’.

def COUNTROW(): #(1 ½ for correct definition of function)


with open("Sdetails.csv",'r', newline='\r\n') as fh:
sreader=csv.reader(fh)
count=0
for r in sreader:
count+=1
print("total record = ",count)
fh.close()
#main program
INSERT()
COUNTROW()

35. Why do we use exceptions in Python programs? List some common exceptions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy