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

BANGALORE SAHODAYA SCHOOLS COMPLEX ASSOCIATION (BSSCA)

Class: XII
PRE-BOARD EXAMINATION (2022-23)
SET 1 ANSWER KEY
DATE : 11.01.23 Max marks : 70
SUBJECT: Computer Science (083) Time : 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is
given in Q34 against part c only.
8. All programming questions are to be answered using Python Language only.

SECTION A
1. Write the type of the tokens for the following 1
i. == ii. :
Ans: Operator and punctuator

2. Given the list 1


odd_square = [x ** 2 for x in range(1, 11) if x % 2 = = 1]
print (odd_square)

Ans: [1, 9, 25, 49, 81]


3. What will be the output of the following Python code? 1
a={1:"A",2:"B",3:"C"}
b=a.copy( )
b[2]="D"
print(a)
a. Error, copy( ) method doesn’t exist for dictionaries
b. {1: ‘A’, 2: ‘B’, 3: ‘C’}
c. {1: ‘A’, 2: ‘D’, 3: ‘C’}
d. “None” is printed
Ans :b{1: ‘A’, 2: ‘B’, 3: ‘C’}

4. Guess the output of the following expression. float(22//3+3/3) 1


a. 8
b. 8.0
c. −8.3
d. 8.333
Ans: b. 8.0

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


total={}
def insert(items):
if items in total:
total[items] += 1
else:
total[items] = 1
insert('Apple')
insert('Ball')
insert('Apple')
print (len(total))
A. 0
B. 1
C. 2
D. 3
Ans : C 2

6. To read the entire remaining contents of the file as a string from a file object infile, we use
____________ 1
a. infile.read(2)
b. infile.read()
c. infile.readline()
d. infile.readlines()
Ans : b infile.read()

7. An attribute in a relation is a foreign key if it is the ___________ key in any other relation.
a. Candidate 1
b. Primary
c. Alternate
d. Foreign
Ans : b Primary

8. The NULL value also means ___________ 1


a) value equal to zero
b) unknown value
c) negative values
d) a large value
Ans: b unknown value

9. Which of the following is False regarding loops in Python? 1


a. Loops are used to perform certain tasks repeatedly.
b. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False
c. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes True.
d. For loop can be used to iterate through the elements of lists.
Ans: c While loop is used when multiple statements are to executed repeatedly until the
given condition becomes True.
10. Suppose you have a table named to test and inside this table you have a column named
CGPA now if you are asked to change the column named CGPA to total percentage, using
alter command then which of the following statement you will write? 1

a. ALTER TABLE test CHANGE COLUMN 'cgpa’ 'total_percentage’ int;


b. ALTER test table CHANGE 'cgpa’ ,'total_percentage’ int;
c. ALTER TABLE test CHANGE 'cgpa 'total_percentage’ int;
d. ALTER test CHANGE column 'cgpa’ 'total_percentage’ int;
Ans: a. ALTER TABLE test CHANGE COLUMN 'cgpa’ 'total_percentage’ int;

11. What is the difference between r+ and w+ modes? 1

a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the
end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at
the end for r+
d) depends on the operating system

Ans: b in r+ the pointer is initially placed at the beginning of the file and the pointer
is at the end for w+

12. Which clause is used to “sort the rows of the final result set by one or more columns”?
a) HAVING 1
b) ORDER BY
c) WHERE
d) FROM
Ans: b ORDER BY

13. Users are able to see a pad-lock icon in the address bar of the browser when there is
___________ connection. 1
a. HTTP
b. SMTP
c. HTTPS
d. FTP
Ans : c. HTTPS

14. What will be the output of the following Python code? 1


i=5
while True:
if i%0O11 == 0:
break
print(i)
i += 1
a. 5 6 7 8 9 10
b. 5 6 7 8
c. 5 6
d. error
Ans: b. 5 6 7 8

15. The referential integrity constraint of a relational database can be specified with the help
of? 1
a. Primary Key
b. Super Key
c. Foreign Key
d. None of the above
Ans : c Foreign Key

16. Which function is used to fetch n number of records from cursor? 1

a. fetch()
b. fetchone()
c. fetchmany()
d. fetchall()
Ans :c. fetchmany( )

17. Assertion - In a function header, any parameter cannot have a default value unless all
parameters appearing on its right have their default values.
Reason - Non- default arguments cannot follow default arguments. 1
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.
Ans : A Both A and R are true and R is the correct explanation of A.

18. Assertion - The with statement simplifies the working with files but does not support
exception handling. 1
Reason – The with statement will automatically close the file after the nested block of code.
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.
Ans : D - A is false but R is true.

SECTION B
19. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code: 2
a=5
work=true
b=hello
c=a+b
FOR i in range(10)
if i%7=0:
continue
Ans:
a=5
work=True
b= ’hello’
c=a+b
for i in range(10):
if i%7= =0:
continue
( ½ mark for each error)

20. How is coaxial cable different from optical fiber? 2


Ans :

Coaxial Cable Optical Fibre


Coaxial cables have solid wire core optical fibers consist of thin strands
surrounded by one or more foil or via of glass Or glass like materials.
Shields,
Coaxial cables transmit electrical signals Optical fibers transmit light signals
or laser signals.
Coaxial cable has finest noise immunity In the optical fiber, there is highest
due to the shield provided. noise immunity as they are
unaffected by the electrical noise
( One mark for each difference )
OR
Write 2 differences between a HUB and a SWITCH.
Ans :
HUB SWITCH
A hub is an electronic device that A switch is a way of routing electricity
connects many computers together to and data flow patterns through circuits
form a single computer network based on binary decisions.
Hubs are cheaper than switches Switches are costlier than Hubs
Network of personal computers can be Network switches inspect data packets
connected together through a central hub as they are received, determining the
source and destination device of
that packet, and forwarding it
appropriately.
( One mark for each difference )

21. a. PREDICT THE OUTPUT 2


t1=("Sahodya",[1,2,'3'],'S',(3,4,6),"Exam",10)
print(t1[-5:-3]+t1[3])
Ans : ([1, 2, '3'], 'S', 3, 4, 6)
( 1 mark for correct anwer)
b. What will be the output of following program:
arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print (sum)
Ans: 4
( 1 mark for correct answer)

22. What is data redundancy? List two problems associated with it. 2
Ans:
Duplication of data is data redundancy.
It leads to problems like wastage of space and inconsistent data in a relation
( 1 mark for each correct answer)

23. Expand the following terminologies. 2


i. WLL ii. MAC.
Ans:
i. WLL Wireless in Local Loop
ii. MAC Media Access Control
(½ mark for every correct full form)

What is Nic?
Ans :
Nic stands for network interface card. It is also known as network adapter. It is in the
form of adding card and is installed in a computer so that the computer can be
connected to our network. Each nic has a Mac address which helps in identify the
computer on a network.

24. Predict the output of the following code. 2


str1=list("Xy82")
for i in range(len(str1)):
if i==3:
x=int(i)
x+=x-3
str1[i]=x
elif (str1[i].islower()):
str1[i]=str1[i].upper()
else:
str1[i]=str1[i]*2
print(str1)

Ans : ['XX', 'Y', '88', 3]


( ½ mark for each value)

OR

A=[1,2,3]
B=[5,6,7]
for i in range(1,3):
A[i-1]=A[i]+1
for i in range(0,3):
print(A[i],end='-')
print()
for i in range(1,3):
B[i-1] =B[i]+1
for i in range(0,3):
print(B[i],end='#')
print()

Ans:
3-4-3-
7#8#7#
(1 mark for each line of correct output)

25. What do you understand by the terms primary key and degree of a relation in relational
data base? Illustrate with an example. 2
Ans:
Primary Key: A primary key is a set of one or more attributes that can uniquely identify
tuples within the relations.
The number of attributes in a relation is called Degree of a relation in relational data base.

Appropriate example to be shown.

(Definitions carry ½ mark each and example carry 1 mark)


OR

Identify the below commands as DDL and DML commands.


CREATE, INSERT, DELETE, DROP,
Ans:
DDL : CREATE, DROP
DML : INSERT, DELETE

SECTION C
26. a. Consider the following two tables :- 1+2
Table : ITEM

I_id ItemName Manufacturer Price


PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000
Table : CUSTOMER

C_id CustomerName City I_id


01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Bangalore PC01
What will be the output of the following statement?
Select CustomerName, City, ItemName, Price from CUSTOMER, ITEM
where CUSTOMER.I_id = ITEM.I_id;
Ans:
C_id City ItemName Price
01 Delhi Laptop 57000
06 Mumbai Personal Computer 32000
12 Delhi Personal Computer 37000
15 Delhi Laptop 57000
16 Bangalore Personal Computer 35000

( 1 mark for correct answer)


b. Write the output of the queries (i) to (iv) based on the table, Books given below:
Table : BOOKS

NO TITLE AUTHOR TYPE PUB QTY PRICE


1 Data Structure Lipschutz DS McGraw 4 217
2 Computer Studies French FND Galgotia 2 75
3 Advanced Pascal Schildt PROG McGraw 4 350
4 Dbase dummies Palmer DBMS Pustak 5 130
5 Mastering C++ Gurewich PROG BPB 3 295
6 Guide Network Freed NET Zpress 3 200
7 Mastering Foxpro Seigal DBMS BPB 2 135
8 DOS Guide Norton OS PHI 3 175
9 Basic for Beginners Norton PROG BPB 3 40
10 Mastering Windows Cowart OS BPB 1 225

i. SELECT TITLE, AUTHOR, PUB FROM BOOKS WHERE TYPE LIKE “OS”;
Ans:
+-------------------+--------+------+
| TITLE | AUTHOR | PUB |
+-------------------+--------+------+
| DOS Guide | Norton | PHI |
| Mastering Windows | Cowart | BPB |
+-------------------+--------+------+

ii. SELECT distinct(PUB) FROM BOOKS WHERE QTY >3;


Ans :
+----------+
| PUB |
+----------+
| McGraw |
| Pustak M |
+----------+

iii. SELECT SUM(PRICE), TYPE FROM BOOKS GROUP BY PUB HAVING PUB LIKE
'BPB';
Ans :
+------------+------+
| SUM(PRICE) | TYPE |
+------------+------+
| 695 | PROG |
+------------+------+
iv. SELECT AVG(PRICE) FROM BOOKS WHERE QTY BETWEEN 1 AND 2;
Ans :
+------------+
| AVG(PRICE) |
+------------+
| 145.0000 |
+------------+
( ½ mark for each correct output)

27. Write a method COUNT_DO() to count the presence of a word ‘do’ in a text file
“MEMO.txt” 3
Example:
If the content of the file is:
I will do it, if you request me to do it.
It would have been done much earlier.
Output should be : 2
Note: In the above example, ‘do’ occurring as a part of the word done is not
considered.
Ans :
def COUNT_DO():
file = open('MEMO.txt', 'r')
count = 0
for line in file:
words = line.split()
for i in words:
if i=='do':
count+=1
file.close()
print("No. of occurences of 'do': ", count)
COUNT_DO()
( ½ mark for correctly opening and closing the file
½ for readlines()
½ mar for correct loop
½ for correct if statement
½ mark for correctly incrementing count
½ mark for displaying the correct output)

OR
Write a method wordcount() which accepts the name of a text file and displays the number
of words present in the file which have the same first and last letter (Ex: Pump, trot).
Ans :
def wordcount(file_name):
file = open(file_name, 'r')
print('Content of given file:')
for line in file:
print(line)
words = line.split()
print('Words having first and last letter same:')
for i in words:
if i[0].lower()==i[-1].lower():
print(i, end = ' ')
file.close()
x = input("Enter file name")
y = x + '.txt'
wordcount(y)
( ½ mark for correctly opening and closing the file
½ for readlines()
½ mar for correct loop
½ for correct if statement
½ mark for correctly incrementing count
½ mark for displaying the correct output)

28. a. Write the outputs of the SQL queries (i) to (iv) based on the relations SCHOOL and
Admin given below: 2+1
SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERIO EXPERI
DS ENCE
1001 UMA SHANKAR ENGLISH 12/03/2000 24 10
1009 NANDITA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 JEEVAN PHYSICS 16/07/1999 28 4
1167 HARISH B CHEMISTRY 19/10/1999 27 5
1215 RAMESH PHYSICS 11/05/1998 22 16
ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD

i. SELECT TEACHERNAME,PERIODS FROM SCHOOL WHERE PERIODS < 25 ORDER BY


TEACHERNAME;
Ans :
TEACHERNAME PERIODS
-------------------- ----------
RAMESH 22
UMA SHANKAR 24
YASHRAJ 24
ii. SELECT TEACHERNAME,ADMIN.CODE, GENDER FROM SCHOOL,ADMIN WHERE
SCHOOL.CODE = ADMIN.CODE AND GENDER LIKE 'FEMALE';
Ans :
TEACHERNAME CODE GENDER
-------------------- ---------- ----------
NANDITA 1009 FEMALE
LISA ANAND 1203 FEMALE
iii. SELECT TEACHERNAME,DESIGNATION FROM SCHOOL, ADMIN WHERE SCHOOL.CODE =
ADMIN .CODE AND SUBJECT LIKE 'ENGLISH';
Ans :
TEACHERNAME DESIGNATION
-------------------- --------------------
UMA SHANKAR VICE PRINCIPAL
LISA ANAND COORDINATOR
iv. SELECT SUBJECT, PERIODS FROM SCHOOL GROUP BY SUBJECT HAVING MIN(PERIODS);
Ans :
SUBJECT PERIODS
----------- ---------
ENGLISH 24
PHYSICS 26
MATHS 24
CHEMISTRY 27
( ½ mark for each query output)

b. Write a command to display the structure of the table “SCHOOL”;


Ans : DESC SCHOOL;
(1 mark for correct answer)

29. Write a definition of a method(function) odd-sum() which receives the list of numbers as
parameter and finds the sum of odd numbers in the list. 3
Example :
Enter a list of no.s[12,53,45,11,66,98,77]
Sum of odd no.s in list 186
Ans:
def odd_sum(x):
sum1 = 0
for i in x:
if i%2!=0:
sum1+=i
print("Sum of odd no.s in list", sum1)
l = eval(input("Enter a list of no.s"))
odd_sum(l)
(½ mark for correct function header
1 mark for correct loop
1 mark for correct if statement
½ mark for printing output)

30. Arr is a list of numbers. Write a function PUSH(Arr), to push all numbers divisible by 5
from the list Arr to the stack. Display the stack if it has at least one element otherwise
display an appropriate message. 3
Ans :
def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)): if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)

(1 mark for correct function header


1 mark for correct loop
½ mark for correct If statement
½ mark for correct display of count)

OR
Write a function in Python, Push(Player) where , Player is a dictionarycontaining the details of
stationary items– {Game:name}.
The function should push the names of those payers into the stack where the name starts with
letter ‘R’. Also display the count of elements pushedinto the stack.
For example:
If the dictionary contains the following data:
Players={"Cricket": “RahulDravid”,"Chess": “R Pragnananda “, "Kho-Kho":
“Sarika Kale”, "Kabaddi": “Pardeep Narwal”}

The stack should contain:


RahulDravid
R Pragnananda
The output should be:
The count of elements in the stack is 2
Ans:
Ans:
stackPlayer=[]
def Push(Player):
count=0
for k inPlayer:
if (Player[k][0] == ‘R’):
stackPlayer.append(k)
count=count+1
print("The count of elements in the stack is : ", count)
(1 mark for correct function header
1 mark for correct loop
½ mark for correct If statement
½ mark for correct display of count)

SECTION D

31. Riana Medicos Centre has set up its new centre in Dubai. It has four
buildings as shown in the diagram given below:
provide the best possible answer for the following queries:
i. Suggest the type of network established between the buildings.
Ans :

ii. Suggest the most suitable place (i.e., building) to house the server of this
Organization. Justify Your answer
Ans :The most suitable place/ building to house the server of this organization would
be building Research Lab, as this building contains the maximum number of computers.

iii. Suggest the placement of the following devices with justification:


a. Repeater b. Hub/Switch
Ans :
a) For layout1, since the cabling distance between Accounts to Store is quite large, so a
repeater would ideally be needed along their path to avoid loss of signals during the
course of data flow in this route. For layout2, since the cabling distance between Store
to Research Lab is quite large, so a repeater would ideally be placed.
b) In both the layouts, a Hub/Switch each would be needed in all the buildings to
interconnect the group of cables from the different computers in each building.
iv. Suggest a system (hardware/software) to prevent unauthorized access to or
from the network.
Ans : Firewall
v. Which service/protocol will be most helpful to conduct live interactions of Experts
from Head Office and people at YHUB locations?
Ans : Videoconferencing OR VoIP
32.
a. Predict the output of the code given below 2+3
Lst1 = ["20","50","30","40"]
CNT = 3
Sum = 0
for I in [7,5,4,6]:
T = Lst1[CNT]
Sum = float (T) + I
print (Sum)
CNT-=1
Ans.
47.0
35.0
54.0
26.0
( ½ mark for each line of output)

b. The code given below reads the following record from the table named Doctors and
displays only those records who are Dermotologists:
DNo – integer
DName – string
Dept – string

Note the following to establish connectivity between Python andMYSQL:

• Username is root
• Password is tiger
• The table exists in a MYSQL database named Hospital.
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 all the
dermotologists
Statement 3- to read the complete result of the query (records of
dermotologists) into the object named content from the
table doctors.

import mysql.connector as ms
def doc_data():
con1=ms.connect(host="localhost", user="root",password="tiger",

database="Hospital")
mycursor= __________________ #Statement 1
print("Details of dermotologists are :")
_______________________ #Statement 2
content = #Statement 3
for i in content:
print(i)
print()

Ans:
Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from doctors where dept like
“Dermotologists” ")
Statement 3: mycursor.fetchall()
(1 mark for each correct answer)
OR
a. Predict the output of the code given below
poet= "ShakESpHerE"
l=len(poet)
r=""
for i in range(l):
if poet[i].islower():
r+=poet[i-1]
elif poet[i].isupper():
if poet[i]=='S':
r+='X';
elif(poet[i]=='E'):
r+=poet[i-1].upper()
else:
r+=chr(ord(poet[i])-1)
print(" Output : ",r)
Ans:
Output : XShaXSHe
(1 mark for first 4 characters, 1 mark for next 4 characters)

b. The code given below inserts the following record in the table teacher:
Tid – integer
TName – string
cls – integer
Dept – string
Note the following to establish connectivity between Python andMYSQL:
✓ Username is root
✓ Password is tiger
✓ The table exists in a MYSQL database named school.
✓ The details (Tid, TName, cls and Dept) are 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
teacher.
Statement 3 – to add the record permanently in the database
import mysql.connector as m
def connecting():
con1=m.connect(host="localhost",user="root", password="tiger",
database="school")
mycursor= ________________#Statement 1
Tid=int(input("Enter Teacher id :: "))
TName=input("Enter Teacher name :: ")
cls=int(input("Enter class thought :: "))
Dept=input("Enter department :: ")
querry="insert into student
values({},'{}',{},{})".format(Tid,TName,cls,Dept)
____________________#Statement 2
____________________# Statement 3
print("Data Added successfully")

Ans :
Statement 1: con1.cursor()
Statement 2: mycursor.execute(querry)
Statement 3: con1.commit()
(1 mark for each correct answer)

33. What is the purpose of using flush() in file handling operations? 5


Sharadhi Patel of class 12 is writing a program to create a CSV file “emp.csv” which will
contain employee code, name and salary of employees. Write a Program in Python that
defines and calls the following user defined functions:
(i) InsRec() – To accept and add data of an employee to a CSV file ‘emp.csv’. Each
record consists of a list with field elements as eid, ename and sal
(ii) search()- To display details of all the employees whose salary is greater than
10000
As a programmer, help him to successfully execute the given task.

Ans : flush() allows the user to send content in file before closing the file. It means when
flush() is used it will clear the buffer and transfer content to file.

import CSV
def InsRec(eid,ename,sal): #to write/add data into the CSV file
fo=open('emp.csv','a')
writer=csv.writer(fo)
writer.writerow([eid,ename,sal])
fo.close()

def search():
fin=open("emp.csv","r",newline='\n')
data=csv.reader(fin)
found=False
print("The Details are")
for i in data:
if ((i[2])>10000):
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()

(1 mark for flush() definition


½ mark for importing csv module
1 ½ marks each for correct definition of InsRec() and search()
½ mark for function call statements )
OR
Give one difference between Text file and Binary File
A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i.Write a user defined function CreateFile() to input data for a record and add to
Book.dat .
ii.Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in
the binary file “Book.dat”
Ans :
Text file contains EOL character at the end of every line, there is no such character in
binary file
import pickle
def createFile():
fobj=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()
def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
(1 mark for flush() definition
½ mark for importing csv module
1 ½ marks each for correct definition of InsRec() and search()
½ mark for function call statements)

SECTION E
34. Sahana is creating a table named Football as shown below in the database sports. 4
Table : Football

TEAMID TEAM_NAME SPONSOR_ID PRICE


TA01 CHELSEA S01 120000
TA02 SUNDERLAND S03 50000
TB03 FULHAM S07 67000
TE04 BLACKPOOL S09 12000
TL05 BLACKBURN ROVERS S03 135000
TM06 MANCHESTER CITY S21 2000000
TT07 BOLTON WANDERERS S25 50000
TT08 WIGAN ATHLETIC S03 25000
Based on the above table answer the following questions :
ii. What will be the cardinality of the table FOOTBALL?
Ans : 4
iii. Which key do you identify as a primary key?
Ans: TEAMID
iv. Write statements to:
a. To add a column named TEAM_COLOR(of 10 characters) to FOOTBALL
Ans : Alter table FOOTBALL add ( TEAM_COLOR varchar(10));
b. To delete tuple with price as 50000
Ans : delete from football where price = 50000
OR (Option for Part iii only)
a. To increase the price of blackpool team to 15000
b. To insert another record as followed:
TT08 WIGAN ATHLETIC S03 25000
Ans : insert into FOOTBALL values (“TT08”, “WIGAN ATHLETIC”, “S03”,
25000
35. Paras Nath Seth is a programmer, who has recently been given a task to write a python
code to perform the following binary file operations with the help of two user defined
functions/modules: 4
a. AddStudents() to create a binary file called STUDENT.DATcontaining student
information – roll number, name and marks (outof 100) of each student.
b. GetStudents() to display the name and percentage of those students who have a
percentage greater than 75. In case there is no student having percentage > 75 the
function displays an appropriate message. The function should also display the
average percent.

He has succeeded in writing partial code and has missed out certain statements, so
he has left certain queries in comment lines. You as an expert of Python have to
provide the missing statements and other related queries based on the following
code of ParasNath.

As a Python expert, help him to complete the following code based on requirement
given above:

import pickle
def AddStudents():
____________# statement1 : to open the binary file towrite data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
#statement2 : to write the list L into the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
__________#statement3: to read from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent = ",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who haspercentage more than 75")
average=Total/Countrec
print("average percent of class = ",average)
AddStudents()
GetStudents()

1. What command should be used to open the file “STUDENT.DAT”for writing


only in binary format in statement1
Ans: F= open("STUDENT.DAT",'wb')

2. What command should be used to write the list L into the binary file,
STUDENT.DAT in statement2
Ans : pickle.dump(L,F) //cannot write small f
3. What command should be used to read each record from the binaryfile
STUDENT.DATin statement3
Ans R = pickle.load(F)

4. Which of the following statement(s) are correct regarding the file access
modes?
a. ‘r+’ opens a file for both reading and writing. File object points to itsbeginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of theexisting
file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwritesthe file if it
exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the fileif the file
exists.
Ans : a
(1 mark for each correct answer)

You might also like