Students must start practicing the questions from CBSE Sample Papers for Class 12 Computer Science with Solutions Set 1 are designed as per the revised syllabus.

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Time Allowed: 3 hours
Maximum Marks: 70

General Instructions:

  • This question paper contains five sections, Section A to E.
  • All questions are compulsory.
  • Section A have 18 questions carrying 01 mark each.
  • Section B has 07 Very Short Answer type questions carrying 02 marks each.
  • Section C has 05 Short Answer type questions carrying 03 marks each.
  • Section D has 03 Long Answer type questions carrying 05 marks each.
  • Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part c only.
  • All programming questions are to be answered using Python Language only.

Section – A

Question 1.
State True or False.
“Variable declaration is implicit in Python.” [1]
Answer:
True

Explanation:
Python doesn’t requires variables to be declared explictly. we can use the variables on a go i.e. whenever a variable is required we can assign a value to it and use it, it automatically gets declared.

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 2.
Which of the following is an invalid datatype in Python? [1]
(A) Set
(B) None
(C) Integer
(D) Real
Answer:
(D) Real

Explanation:
Python has the following built-in data types by default:

Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: diet
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, byte array, memoryview
None Type: None

Question 3.
Given the following dictionaries
dict_exam={“Exam”:”AISSCE”, “Year”:2 023}
dict_result={“Total”:500, “Pass_Marks”:165}
Which statement will merge the contents of both dictionaries? [1]
(A) dict_exam.update(dict_result)
(B) dict_exam + dict_result
(C) dict_exam.add(dict_result)
(D) dict_exam.merge(dict_result)
Answer:
(A) dict_exam.update(dict_result)

Explanation:
update function is used to add a key;value pair to an existing dictionary

Question 4.
Consider the given expression: [1]
not True and False or True
Which of the following will be correct output if the given expression is evaluated?
(A) True
(B) False
(C) NONE
(D) NULL
Answer:
(A) True

Explanation:
The expression is evaluated according to the operator hierarchy, i.e first NOT will be evaluated then AND and then OR.

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 5.
Select the correct output of the code: [1]
a = “Year 2022 at All the best” a = a.split (‘2’)
b = a[0] + “. ” +a[l] + “. ” +a[3]
print (b)
(A) Year. 0. at All the best
(B) Year 0. at All the best
(C) Year . 022. at All the best
(D) Year . 0. at all the best
Answer:
(A) Year. 0. at All the best

Explanation:
split function splits the string into a list, where each element is separated by the character specified or white space(by default), here the string will be split at every occurrence of 2. elements of the list will be [“Year”, “0”, “at All the best”]

Question 6.
Which of the following mode in file opening statement results or generates an error if the file does not exist? [1]
(A) a+
(B) r+
(C) w+
(D) None of the above
Answer:
(B) r+

Explanation:
a, a+, w &w+ modes open an existing file for reading as well as writing, if the file doesn’t eixst it is created. r+ mode opens file for reading as well as writing, it generates an error if the file doesn’t exist.

Question 7.
Fill in the blank:
____________ command is used to remove primary key from the table in SQL. [1]
(A) update
(B) remove
(C) alter
(D) drop
Answer:
(C) alter

Explanation:
Any change in the structure of a table is implemented using ALTER

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 8.
Which of the following commands will delete the table from MYSQL database? [1]
(A) DELETE TABLE
(B) DROP TABLE
(C) REMOVE TABLE
(D) ALTER TABLE
Answer:
(B) DROP TABLE

Explanation:
DROP Table command is used to delete a table from the database.

Question 9.
Which of the following statement(s) would give an error after executing the following code? [1]
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 1
(A) Statement 3
(B) Statement 4
(C) Statement 5
(D) Statement 4 and 5
Answer:
(B) Statement 4

Explanation:
strings in Python are immutable, once created their value can’t be changed in place, so the statement S[0]=’@’ will give an error.

Question 10.
Fill in the blank:
____________ is a non-key attribute, whose values are derived from the primary key of some other table. [1]
(A) Primary Key
(B) Foreign Key
(C) Candidate Key
(D) Alternate Key
Answer:
(B) Foreign Key

Explanation:
Primary key of one table acts as a foreign key for some other table. Its value domain is the primary key attribute of the table of which it is a primary key.

Question 11.
The correct syntax of seek() is: [1]
(A) file_object. seek (of f set [, ref erence_point] )
(B) seek(offset [, reference_point])
(C) seek (offset, file_object)
(D) seek.file_object (offset)
Answer:
(A) file_object. seek (of f set [, ref erence_point] )

Explanation:
seek() is used to place the file pointer at a specific location in the file. For this we need to specify the number of bytes from the reference point after which the pointer should be placed, the offset can be 0(beginning),l (current location) or 2 (EOF).

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 12.
Fill in the blank:
The SELECT statement when combined with ____________ clause, returns records without repetition. [1]
(A) DESCRIBE
(B) UNIQUE
(C) DISTINCT
(D) NULL
Answer:
(C) DISTINCT

Explanation:
DISTINCT clause in SELECT statement is used to display records without repetition. DESCRIBE clause is used to display table structure. Unique displays records that have unique values of a field and null is used to specify null value.

Question 13.
Fill in the blank
____________ is a communication methodology designed to deliver both voice and multimedia communications over Internet protocol. [1]
(A) VoIP
(B) SMTP
(C) PPP
(D) HTTP
Answer:
(A) VoIP

Explanation:
VoIP is Voice Over Internet protocol and is used to transfer audios and videos over internet.

Question 14.
What will the following expression be evaluated to in Python? [1]
print (15.0 / 4 + (8 + 3.0))
(A) 14.75
(B) 14.0
(C) 15
(D) 15.5
Answer:
(A) 14.75

Explanation:
(15.0/4+ (8+3.0))
= (15.0/4+11.0)
= 3.75+11.0
= 14.75

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 15.
Which function is used to display the total number of records from table in a database? [1]
(A) sum(*)
(B) total (*)
(C) count (*)
(D) return (*)
Answer:
(C) count (*)

Explanation:
count () is used to count number of records in a table with a specified criterion. * is used to specify all. count(*) will count all the records in a table.

Question 16.
To establish a connection between Python and SQL database, connect () is used. Which of the following arguments may not necessarily be given while calling connect () ? [1]
(A) host
(B) database
(C) user
(D) password
Answer:
(B) database

Explanation:
connect() is used to establish a connection to mysql server, database can later be specified using setdatabase(). So specifying database in connect() is not necessary.

Assertion and Reason:
In the following questions, A statement of Assertion (A) is followed by a statement of Reason (R). Mark the correct choice as. [1]
(A) Both A and R are true and R is the correct explanation of A.
(B) Both A and R are true and R is not the correct explanation of A.
(C) A is true but R is false.
(D) A is false but R is true.

Question 17.
Assertion (A): If the arguments in function call statement match the number and order of arguments as defined in the function definition, such arguments are called positional arguments.
Reason (R): During a function call, the argument list first contains default argument(s) followed by positional argument(s). [1]
Answer:
(C) A is true but R is false.

Explanation:
During a function call, the argument list first contains positional argument(s). default argument(s) are not specified during the function call as their default value is taken up.

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 18.
Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text file. Reason (R): The information is organized with one record on each line and each field is separated by comma. [1]
Answer:
(A) Both A and R are true and R is the correct explanation of A.

Explanation:
Since all the data is arranged separated by a comma, and each record takes up a new line such files are called csv files.

Section – B

Question 19.
Rao 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') [2]

Answer:

def prime():
n=int(input("Enter number to check :: ")) ttbracket 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

Question 20.
Write two points of difference between Circuit Switching and Packet Switching. [2]
OR
Write two points of difference between XML and HTML.
Answer:

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

OR

XML (Extensible MarkupLangauge)

  • XML tags are not predefined, they are user defined
  • XML stores and transfers data.
  • Dynamic in nature

HTML (Hypertext Markup Langauge)

  • HTML tags are pre-defined and it is a markup language
  • HTML is about displaying data.
  • Static in nature

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 21.
(a) Given is a Python string declaration:
myexam=”@@CBSE Examination 2022@@”
Write the output of: print (myexam [: : -2 ] )
(b) Write the output of the code given below:
my_dict = {“name”: “Aman”, “age”: 26} ‘
my_dict[1 age 1] = 2 7
my_dict[1 address 1] = “Delhi”
print (my_dict. items () ) [2]
Answer:
a. @20 otnmx SC@
b. dict_items([(‘name’, ‘Aman’), (‘age’, 27), (‘address’, ‘Delhi’)])

Question 22.
Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give example to support your answer. [2]
Answer:
A foreign key is used to set or represent a relationship between two relations ( or tables) in a database. Its value is derived from the primary key attribute of another relation.

For example:
In the tables TRAINER and COURSE given below, TID is primary key in TRAINER table but foreign key in COURSE table.
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 2

Question 23.
(a) Write the full forms of the following:
(i) SMTP
(ii) PPP
(b) What is the use of TELNET? [2]
Answer:
(a) (i) SMTP: Simple Mail Transfer Protocol
(ii) PPP: Point to Point Protocol

(b) TELNET is used to access a remote computer / network.

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 24.
Predict the output of the Python code given below: def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),1#1, end=1 ‘)
OR
Predict the output of the Python code given below:
tuplel = (11, 22, 33, 44, 55 ,66)
listl =list (tuple1)
new_list = []
for i in listl:
if i%2==0:
new_lis t.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
Answer:
22 # 40 # 9 # 13 #
OR
(22, 44, 66)

Question 25.
Differentiate between count() and count(*) functions in SQL with appropriate example. [2]
OR
Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP
Answer:
COUNT(*) returns the count of all rows in the table, whereas COUNT () is used with Column_Name passed as argument and counts the number of non-NULL values in a column that is given as argument.
Example: Table: EMPL
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 3

OR

DDL – ALTER, DROP
DML – INSERT, UPDATE

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Section – C

Question 26.
(a) Consider the following tables – Bank Account and Branch:

Table: Bank_Account

Acode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current

Table: Branch

Acode City
A01 Delhi
Ao2 Mumbai
A03 Nagpur

What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;
(b) Write the output of the queries (i) to (iv) based on the table, TECH_COURSE given below:
Table: TECH_COURSE
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 4
(i) SELECT DISTINCT TID FROM TECH_COURSE;
(ii) SELECT TID, COUNT ( * ), MIN (FEES) FROM TECH_COURSE GROUP BY TID HAVING COUNT (TID) >1 ;
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000 ORDER BY CNAME;
(iv) SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 15000 AND 17000; [1+2=3]
Answer:
(a)
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 5

(b) (i)

DISTINCT TID
101
NULL
102
104
103

(ii)

TID COUNT (*) MIN (FEES)
101 2 12000

(iii)

CNAME
Digital Marketing
Mobile Application Development

(iv) 15500.00

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 27.
Write a method COUNTLINES() in Python to read lines from text file TESTFILE.TXT’ and display the lines which are not starting with any vowel.
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 COUNTLINES() function should display the output as:
The number of lines not starting with any vowel -1 [3]
OR
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
Answer:

def COUNTLINES() :
file = open ('TESTFILE.TXT', 'r ' )
lines = file . readlines ()
count=0
for w in lines :
if (w[0]).lower() not in 'aeoiu':
count = count + 1
print ("The number of lines not starting with any vowel: ", count)
file . close ()
COUNTLINES ()

OR

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 ()

Question 28.
(a) Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and Placement given below:
Table : Teacher
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 6

Table : Placement

P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur

(i) SELECT Department, avg(salary) FROM Teacher GROUP BY Department;
(ii) SELECT MAX (Date_of_Join) , MIN (Date_of_Join) FROM Teacher;
(iii) SELECT Name, Salary, T.Department, Place FROM Teacher T, Placement P WHERE T.Department = P.Department AND Salary>20000;
(iv) SELECT Name, Place FROM Teacher T, Placement P WHERE Gender =’F’ AND T.Department=P.Department;
(b) Write the command to view all tables in a database. [3]
Answer:
(i)

Department Avg (Salary)
Computer Sc 16500.00
History 30000.00
Mathematics 25000.00

(ii)

Max (Date_of_Join) Min (Date_of_Join)
2021-09-05 2017-03-04

(iii)
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 7

(iv)

Name Place
Samira Ahmedabad
Suman Ahmedabad
Shalaka Jaipur

(b) SHOW TABLES;

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 29.
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] [3]
Answer:
def INDEX_LIST(L):
indexList= []
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList

Question 30.
A list contains following record of a customer:
[Customer name, Phone number, City]
Write the following user defined functions to perform given operations on the stack named ‘status’:
(i) Push_element() – To Push an object containing name and Phone number of customers who live in Goa to the stack
(ii) Pop_element() – To Pop the objects from the stack and display them. Also, display “Stack Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777″,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain [“Ashmit”,”1010101010″]
[“Gurdas”,”9999999999″]
The output should be:
[“Ashmit”,”1010101010″]
[“Gurdas”,”9999999999″]
Stack Empty [3]
OR
Write a function in Python, Push(SItem) where, SItem is a dictionary containing the details of stationary items- {Sname:price}.
The function should push the names of those items in the stack who have price greater than 75. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem={,’Pen”:106,”Pencil”:59,”Notebook”:80,”Eraser”:25}
The stack should contain Notebook
Pen
The output should be:
The count of elements in the stack is 2
Answer:

status=[ ]
def Push_element(cust):
if cust[2]=="Goa":
L1=[oust[0] ,cust [1]]
status.append(L1)
def Pop_element ():
num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele) num=num-1
else:
print("Stack Empty")

OR

stackltem=[ ]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75):
stackltem.append(k)
count=count+l
print("The count of elements in the stack is : ", count)

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Section – D

Question 31.
Make ln lndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres in various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus, they are planning to have 3 different blocks for App development, Web designing and Movie editing. Each block has number of computers, which are required to be connected in a network for communication, data and resource sharing. As a network consultant of this company, you have to suggest the best network related solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between various blocks/locations and other given parameters.
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 8

Distance between various blocks/locations:

Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 m

Number of computers

Block Number of Computers
App development 75
Web designing 50
Movie editing 80

(i) Suggest the most appropriate block/location to house the SERVER in the Kashipur campus (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
(ii) Suggest a device/software to be installed in the Kashipur Campus to take care of data security.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect various blocks within the Kashipur Campus.
(iv) Suggest the placement of the following devices with appropriate reasons:
a. Switch / Hub
b. Repeater
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur Campus
and Mussoorie Campus. [5]
Answer:
(i) Movie editing block is the most appropriate to house the server as it has the maximum number of computers.

(ii)
Firewall

(iii)
Ethernet Cable

Layout:
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 9

(iv) Switch/hub will be placed in all blocks to have connectivity within the block.
Repeater is not required between the blocks as the distances are less than 100 mts.

(v)
Protocol: VoIP

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 32.
(a) Write the output of the code given below:
p=5

def sum(q,r=2):
global p
p=r+q**2
print(p, end= '#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)

(b) The code given below inserts the following record in the table Student:
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.
  • The details (RollNo, Name, Class 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():
conl=mysql.connect(host="localhost",user="root",
password="tiger", database="school") .
mycursor=______________#Statement 1
rno=int(input("Enter Roll Number :: "))
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") [5]

OR

(a) Predict the output of the code given below:
s=”welcome2cs” ‘
n = len(s)
m= ” ”
for i in range(0, n):
if (s[i] >= ‘a’ and s[i] <= ‘m’):
m = m +s[i] .upper ()
elif (s[i] >= ‘n’ and s[i] <= ‘z’) :
m = m +s[i-1]
elif (s [i] .isupper()) :
m = m + s[i].lower()
else:
m = m + ‘ & ‘
print(m)

(b) The code given below reads the following record from the table named student and displays only those ,
records who have marks greater than 75:
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.

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 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():
coni=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()
Answer:
(a) Output:
105#6#

(b) Statement 1:
conl.cursor()
Statement 2:
mycursor. execute (querry)
Statement 3:
conl.commit()

OR

(a) sELCcME&Cc

(b) Statement 1:

coni.cursor()
Statement 2:
mycursor.execute("select * from student where Marks>75")
Statement 3:
mycursor.fetchall()

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 33.
What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a list with field elements as empid, name and mobile to store employee id, employee name and employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’. [5]
OR
Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists of a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price respectively.
(ii) search()- To display the records of the furniture whose price is more than 10000.
Answer:
Advantage of a csv file:

  • It is human readable – can be opened in Excel and Notepad applications
  • It is just like text file

Program:

import csv
def ADD():
fout=open ("record. csv", "a" , newline="\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(1st)
fout.close( )
def COUNTR( ):
fin=open("record.csv","r",newline="\n")
data=csv. reader (fin)
d=list(data)
print(len(d))
fin.close ( )
ADD( )
COUNTR( )

OR

Difference between binary file and csv file :
(Anyone difference may be given)
Binary file:

  • Extension is .dat
  • Not human readable
  • Stores data in the form of Os and Is

CSV file

  • Extension is .csv
  • Human readable
  • Stores data like a text file Program:
import csv
def add():
fout=open("furdata.csv","a", newline='\n1 ) wr=csv.writer(fout)
fid=int(input("Enter Furniture Id :: ") )
fname=input("Enter Furniture name :: ")
fprice=int(input("Enter price :: "))
FD= [fid, fname, fprice]
wr.writerow(FD)
fout.close()
def search():
fin=open("furdata.csv","r",newline=1\n')
data=csv. reader (fin)
found=False
print("The Details are")
for i in data:
if int(i[2])>10000:
found=True
print(i[0] ,i [1] ,i [2])
if found==False:
print("Record not found")

fin. close ()
add ()
print("Now displaying")
search()

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Section – E

Question 34.
Navdeep creates a table RESULT with a set of records to maintain the marks secured by students in Sem 1, Sem2, Sem3 and their division. After creation of the table, he has entered data of 7 students in the table.
CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions 10
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table
Roll No-108, Name- Aadit, Semi- 470, Sem2-444, Sem3-475, Div -1.
b. Increase the SEM2 marks of the students by 3% whose name begins with ‘N’. [1+1+2=4]
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing IV division.
b. Add a column REMARKS in the table with datatype as varchar with 50 characters
Answer:
(i) ROLL_NO

(ii) New Degree: 8
New Cardinality: 5

(iii) (a) INSERT INTO RESULT VALUES (108, Aadit’, 470, 444, 475, ‘I’);
b. UPDATE RESULT SET SEM2=SEM2+ (SEM2*0.03) WHERE SNAME LIKE “N%”;

OR (Option for Part iii only)

a. DELETE FROM RESULT WHERE DIV=’IV’;
b. ALTER TABLE RESULT ADD (REMARKS VARCHAR(50));

CBSE Sample Papers for Class 12 Computer Science Set 1 with Solutions

Question 35.
Aman is a Python programmer. He has written a code and created a binary file record. dat with employee id, 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 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:
printt ('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)
(ii) Write the correct statement required to open a temporary file named temp. dat. (Statement 2)
(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? [1+1+2=4]
Answer:
(i) pickle
(ii) fout=open(‘temp.dat’, ‘wb’)
(iii) Statement 3: pickle.load(fin)
Statement 4: pickle.dump(rec,fout)