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 Hrs.
Max. Marks : 70
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 3 questions (31 to 33). Each question carries 5 Marks.
- Section E, consists of 2 questions (34 to 35). Each question carries 4 Marks.
- All programming questions are to be answered using Python Language only.
Section-A
Question 1.
State True OR False. [1]
“In a Python program, if a break statement is given in a nested loop, it terminates the execution of all loops in one go.”
Answer:
False
Explanation:
The break statement, in a nested loop terminates the current loop. It does not come out of other loops in which the current loop is nested.
Question 2.
In a table in MySQL database, an attribute A of datatype varchar(20) has the value “Keshav”. The attribute B of datatype char(20) has value “Meenakshi”. How many characters are occupied by attribute A and attribute B? [1]
(a) 20.6
(b) 6.20
(c) 9.6
(d) 6.9
Answer:
(b) 6.20
Explanation:
Here, Keshav has 6 characters. In contrast to char data type, varchar is variable length. So inspite of width of the field being 20, it will use only the number of characters in the data. Instead char is fixed length. It will occupy as many characters as is reserved while table creation.
Question 3.
What will be the output of the following statement? [1]
print(3-2**2**3 + 99/11)
(a) 244
(b) 244.0
(c) -244.0
(d) Error
Answer:
(c) – 244.0
Explanation:
The original expression is:
(3-2**2**3 + 99/11) = 3 – 2**8 + 9.0 ;
= 3 – 256 + 9.0 = -253 + 9.0 = -244.0
Question 4.
Select the correct output of the code: [1]
S = "Python is fun" I = s.split() s_new = "-".join ([1[0], upper(), I[1], I[2], capitalise()]) print(s_new)
(a) PYTHON-IS-Fun
(b) PYTHON-is-Fun
(c) PYTHON-is-Fun
(d) PYTHON-Is-Fun
Answer:
(b) PYTHON-is-Fun
Explanation:
S = "Python is fun" I = s.split() s_new = "-".join ([1[0], upper(), I[l], l[2], capitalise()]) pririt(s_new) s.split():
The split() function splits a sentence on basis of a delimiter and returns a list of strings split on the delimiter specified.
Here the split() statement returns a list L = [“Python”, “is”, “fun”]
The upper() function converts a string to uppercase
L[0].upper() returns PYTHON, L[1] returns “is” and L[2].capitalize() returns Fun. “-“.join merges all the three strings separated by “-“,
Question 5.
In MySQL database, if a table, Alpha has degree 5 and cardinality 3, and another table, Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian product of Alpha and Beta? [1]
(a) 5.3
(b) 8.15
(c) 3.5
(d) 15.8
Answer:
(b) 8.15
Question 6.
Riya wants to transfer pictures from her mobile phone to her laptop. She uses Bluetooth Technology to connect two devices. Which type of network will be formed in this case? [1]
(a) PAN
(b) LAN
(c) MAN
(d) WAN
Answer:
(a) PAN
Explanation:
When multiple personal devices are connected within a small area it is called PAN Personal area network. Here the user connects her mobile to the laptop, hence it forms a PAN.
Question 7.
Which of the following will delete key-value pair for key = “Red” from a dictionary D1? [1]
(a) delete D1(“Red”)
(b) del D1[“Red”]
(c) del.D1[“Red”]
(d) D1.del[“Red”]
Answer:
(b) del D1 [“Red”]
Explanation:
The del function requires the key of the key-value pair to be deleted.
Question 8.
Consider the statements given below and then choose the correct output from the given options: [1]
pride="#G20 Presidency" print(pride[-2:2:-2])
(a) ndsr
(c) ceieP
(b) ceiePO
(d) yndsr
Answer:
(b) ceiePO
Explanation:
The index positions of the characters in the string are as follows :
# | G | 2 | o | P | r | e | s | i | d | e | n | c | y | |
-15 | -14 | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -l |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
In the statement print(pride[-2 :2: -2]):- The slicing operation is extracting characters from position -2 up to position 2 jumping by 2 positions backwards.
Question 9.
Which of the following statement(s) would give an error during execution of the following code? [1]
tup = (20,30,40,50,80,79) print(tup) # Statement 1 print(tup[3]+50) # Statement 2 print(max(tup)) # Statement 3 tup[4] = 80
(a) Statement 1
(b) Statement 2
(c) Statement 3
(d) Statement 4
Answer:
(d) Statement 4
Explanation:
The insert statement will not work on tuples as tuples are immutable and statement 4 tries to change the value of a tuple.
Question 10.
What possible outputs(s) will be obtained when the following code is executed? [1]
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*
(b) YETLOW*
WHITE*
BLACK*
RED*
(c) WHITE*WHITE*
YELLOW* YELLOW*
BLACK*BLACK*
RED*RED*
(d) YELLOW*
WHITE* WHITE*
BLACK* BLACK* BLACK*
RED* RED* RED* RED* RED*
Answer:
(b) YELLOW*
WHITE*
BLACK*
RED*
Explanation:
The for loop “for I in color”, takes values beginning with “YELLOW”. Therefore first value in output must be “YELLOW”. So options (b) or (d) are possible. As in both options YELLOW is printed once, it indicates that the value of myNumber must be 2, therefore the inner loop will go for only one time. So the other values in the color list will be printed once.
Question 11.
Fill in the blank:
The modem at the sender’s computer end acts as a _____.
(a) Model
(b) Modulator
(c) Demodulator
(d) Convertor
Answer:
(b) Modulator
Explanation:
The data carried by the sender machine is in digital format, which must be converted to analog before transmission. Hence at the sender end the modem acts as a modulator.
Question 12.
Consider the code given below: [1]
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?
Options:
(a) global a
(b) global b=100
(c) global b
(d) global a = 100
Answer:
(c) global b
Explanation:
To access the global variable b, global keyword has to be used.
Question 13.
State whether the following statement is True or False: [1]
An exception may be raised even if the program is syntactically correct.
Answer:
True
Explanation:
An exception is an unusual situation in a program execution. There are different types of exceptions that may occur for various reasons such as “ArraylndexError”, “Invalid Inputs” “Keyboard error” etc. So even if the program is syntactically correct exception can occur.
Question 14.
Which of the following statements is FALSE about keys in a relational database? [1]
(a) Any candidate key is eligible to become a primary key.
(b) A primary key uniquely identifies the tuples in a relation.
(c) A candidate key that is not a primary key is a foreign key.
(d) A foreign key is an attribute whose value is derived from the primary key of another relation
Answer:
(c) A candidate key that is not a primary key is a foreign key.
Explanation:
Even if a field is a candidate key, it may not be a foreign key, as it must exist in the other table for linking the two tables. Moreover candidate keys cannot carry duplicate values.
Question 15.
Fill in the blank: [1]
In case of _____ switching, before a communication starts, a dedicated path is identified between the sender and the receiver.
Answer:
Circuit switching
Question 16.
Which of the following functions changes the position of file pointer and returns its new position? [1]
(a) flush()
(c) .seek()
(b) tell()
(d) offset()
Answer:
(c) .seek()
Explanation:
.seek() function places the file pointer at a specific byte position which is indicated as its parameter.
Q. 17 and 18 are ASSERTION AND REASONING 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.
Question 17.
Assertion (A): List is an immutable data type. [1]
Reason (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.
Answer:
(d) A is false, but R is True.
Explanation:
A List is not immutable. Its values can be changed. Immutable types, if tried to be changed, either an error is thrown or the old variable is destroyed and a new memory is allocated.
Question 18.
Assertion (A): Python standard library consists of number of modules. [1]
Reason (R): A function in a module is used to simplify the code and avoids repetition.
Answer:
(b) Both A and R are true and R is not the correct explanation for A.
Explanation:
Both the statements are True. The reason statement is correct, but it does not justify the Assertion given.
Section-B
Question 19.
(i) Expand the following terms:
POP3, URL
(ii) Give one difference between XML and HTML. [2]
Answer:
(i) Full forms:
POP3 — Post Office Protocol 3
URL — Uniform Resource Locator
(ii) Differences between HTML and XML:
HTML | XML |
It displays formatted data, but cannot transport data | It is used to carry data between heterogenous platforms. |
We use pre-defined tags | we can define our own tags and use them |
Hyper text mark Up language | Extensible Markup Language |
Static web development language | Dynamic web development language. |
HTMLis not case sensitive | It is case sensitive |
Question 20.
The code given below accepts a number as an argument and returns the reverse number. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made. [2]
define revNumber(num): rev = 0 rem = 0 While num >0: rem = num %10 rev = rev*10 + rem num = num//10 return rev print (revNumber(1234))
Answer:
def revNumber(num): rev = 0 rem = 0 While num > 0: rem = num %10 rev = rev*10 + rem num = num//10 , return rev print (revNumber(1234))
Explanation:
- The “def” keyword defines a function f
- “while” should be written in lowercase not as “While” ‘
- The return statement will be the last statement of the while loop. So indentation should be done accordingly.
Question 21.
Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument and displays the names (in uppercase)of the places whose names are longer than 5 characters. [2]
For example, Consider the following dictionary.
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be:
LONDON NEW YORK
OR
Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string.
For example, if the string is “Come let us have some fun”, the tuple will have (4, 3, 2, 4,4, 3)
Answer:
PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Dubai"} def countNow(PLACES): for place in PLACES.values(): if len(place)>5: print(place.upper()) countNow(PLACES)
OR
def lenWords(STRING): T = () L = STRING. split() for word in L: length = len(word) T = T + (length) return T
Explanation:
For 1st option code:
The for loop uses the membership operator “in” to get the values of the dictionary and then uses the len() function to check their lengths, whether they are more then 5 or not. In these cases the values are converted to uppercase and printed.
For 2nd option code:
In this code the split() function is used to seperate the string into words, which returns a list L . carrying each word as a list item. The for loop picks each word from the list and finds the length of – each. It then adds the length found as an element of the tuple.
Question 22.
Predict the output of the following code: [2]
S = "LOST" L = [10, 21, 33, 4] D = { } for I in range (len(S)): if I%2==0: D[L.pop()] = S[1] else: D[L.pop()] = I + 3 For K,V in D.items(): print (K, V, sep = "*")
Answer:
4*L
33*4
21*S
10*6
Explanation:
S = "LOST" L = [10, 21, 33, 4] D = { } for I in range (len(S)): if I%2==0: D[L.pop()] = S[1] else : D[L.pop()] = I + 3 For K, V in D.items(): print (K, V, sep = "*")
The loop traverses through the values 0, 1, 2, 3. If I is even the statement D[L.pop()] pops the last element from the list L and adds it as a dictionary key. The value of the key is taken as S[I] that is character at index I of the string S.
In the last for loop, each dictionary key and value is taken from D.items() and printed with a separator =”*”
Question 23.
Write the Python statement for each of the following tasks using BUILT-IN functions/methods only: [1+1=2]
(i) To insert an element 200 at the third position, in the list LI.
(ii) To check whether a string named, message ends with a full stop / period or not.
Answer:
(i) L1.insert(2,200)
(ii) message.endswith(“.”)
Explanation:
- If the insert() function is used for a list, it inserts an element at the index specified.
- The endswith() function checks whether a string is suffixed with a specific string or not and returns a boolean True/False.
Question 24.
Ms. Shalini has just created a table named “Employee” containing columns Ename, Department and Salary.
After creating the table, she realized that she has forgotten to add a primary key column in the table. .Help her in writing an SQL command to add a primary key column Empld of integer type to the table Employee.
Thereafter, write the command to insert the following record in the table: [2]
Emp Id- 999
Ename- Shweta
Department: Production
Salary: 26900
Answer:
Part 1:
ALTER TABLE Employee ADD Empld INTEGER PRIMARY KEY;
Part 2:
INSERT INTO Employee VALUES(“Shweta”,”Production”,26900,999);
OR
INSERT INTO Employee (EmpId, Ename, Department, Salary) VALUES (999, “Shweta”, “Production”, 26900);
Explanation:
Alter table command which is a DDL, can be used to make changes to the structure of the table, that is to add, modify and remove a field.
Constraints can also be added by the Alter table command
Syntax:
ALTER TABLE ADD PRIMARY KEY;
To add records to a table, the command takes the form : Insert into <table> values (val1,val2,val3,……)
Question 25.
Predict the output of the following code: [2]
def changer (P, Q = 10): P=P/Q Q=P%Q return P A = 200 B=20 A = Changer (A, H) print (A, B, sep ='$') B = Changer (B) print (A, B, sep = ‘$‘, end ='###')
Answer:
Output:
10.0$20 10.0$2.0### def changer (P, Q = 10): P=P/Q Q=P%Q return P A = 200 B = 20 A = Changer (A, B) print (A, B, sep = '$') B = Changer (B) print (A, B, sep = '$', end = '###')
Explanation:
In the code the function receives a value for the argument P and a default argument value as Q = 10.
When the function is called first the values received in P, Q are 200,20 The statement P = P/Q makes P = 200/20 = 10.0 and Q = P%Q = 10.0%10 =0. The value of P is returned back to A = 10.0.
The print statement prints values of A,B which are 10.0 and 20 with a separator $.
In the 2nd call the values received by P and Q are 20,10( The default value).P=P/Q makes P as 2.0. Value of P =2.0 is returned into B. Hence, the values printed are 10.0, 2.0 with separator ‘$’ and ending with “###”
Section-C
Question 26.
Predict the output of the Python code given below: [3]
Text 1 = "I ND-23" Text 2 = " " I = 0 while I < len (Text 1): if Text 1 [I] >= "0" and Text 1 [I] < "9" : Val = int (Text 1 [I]) Val = Val + 1 Text 2 = Text 2 + str (Val) elif Text 1 [I] >="A" and Text 1 {I]< = "Z" : Text 2 = Text 2 + (Text 1 [I + 1]) else: Test 2 = Text 2 + "*" I + = 1 print (Text 2)
Answer:
Output: ND-*34
Explanation:
Text 1 = "IND-23" Text 2 = " " I = 0 while I < len (Text 1): if Text 1 [I] >= "0" and Text 1 [I] < "9" : Val = int (Text 1 [I]) Val = Val + 1 Text 2 = Text 2 + str (Val) elif Text 1 [I] >="A" and Text 1 {I]< = "Z" : Text 2 = Text 2 + (Text 1 [I +1]) else: Test 2 = Text 2 + "*" I + = l print (Text 2)
The while loop traverses through the length of Textl with I taking the values 0, 1, 2, 3, 4, 5.
Certain conversions are done inspecting the values of the characters.
(a) For digits, it converts it into integer form, increments the digit by 1 and appends it to Text2
(b) If it is an uppercase alphabet the next character in the text is appended to Text2, otherwise a is appended to Text2
Question 27.
Consider table CLUB given below and write the output of the SQL queries that follow: [3]
CID | CNAME | AGE | GENDER | SPORTS | PAY | DOAPP |
5246 | AMRITA | 35 | FEMALE | CHESS | 900 | 2006-03-27 |
4687 | SHYAM | 37 | MALE | CRICKET | 1300 | 2004-04-15 |
1245 | MEENA | 23 | FEMALE | VOLLEYBALL | 1000 | 2007-06-18 |
1622 | AMRIT | 28 | MALE | KARATE | 1000 | 2007-09-05 |
1256 | AMINA | 36 | FEMALE | CHESS | 1100 | 2003-08-15 |
1720 | MANJU | 33 | FEMALE | KARATE | 1250 | 2004-04-10 |
2321 | VIRAT | 35 | MALE | CRICKET | 1050 | 2005-04-30 |
(i) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;
(ii) SELECT CNAME, SPORTS FROM CLUB WHERE DOAPP<“2006-04-30” AND CNAME LIKE “%NA”;
(iii) SELECT CNAME, AGE, PAY FROM CLUB WHERE GENDER = “MALE” AND PAY BETWEEN 1000 AND 1200;
Answer:
Explanation:
(i) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;
Count() function counts the number of records. Distinct is used to get unique values. Here count(distinct sports) counts the number of unique sports values in the club table.
(ii) SELECT CNAME, SPORTS FROM CLUB WHERE DOAPP<“2006-04-30” AND CNAME LIKE “%NA”;
This query displays CNAME and SPORTS from the CLUB table for records whose DOAPP is before the date specified and whose CNAME ends with “NA”. The “%NA” specifies values ending with “NA”
(iii) SELECT CNAME, AGE, PAY FROM CLUB WHERE GENDER = “MALE” AND PAY BETWEEN 1000 AND 1200;
This query displays CNAME, AGE and PAY of “MALES” and whose PAY lies between 1000 and 1200. The Between cause matches values in a range.
Question 28.
Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with the word ‘You’. [3]
OR
Write a function, vowelCount() in Python that counts and displays the number of vowels in the text file named Poem.txt.
Answer:
def test(): fObj1 = open("Alpha.txt", "r" data = fObj1.readlines() for line in data: L = line.split() if L[0] = "You" : print(line) fObj1.close()
Explanation:
The 1st statement in the function opens the text file in read mode. In the 2nd statement the readlines() function reads all the data of the text file as separate lines into a list “data”. The for loop picks each line from the data and the split() functions creates a list L of the words of each line. L[0] gives the first word of each line. The if condition checks if the word is “You”, and prints the line in case of a match.
OR
déf vowelCount(): fObj = open(”Alpha.txt “,“ “r”) data = str(fObj.read()) cnt = 0 for ch_in data: if ch in “aeiouAEIOU”: cnt=cnt + 1 prìnt(cnt) fObj.close()
Explanation:
The 1st statement in the function opens the text file in read mode. The read () function reads all the data of the text into a string “data”. The for loop picks each character from the data and checks whether it is a vowel or not. In case of a match a count is incremented, which is finally printed.
Question 29.
Consider the table Personal given below: [3]
Table:Personal
P_ID | Name | Desig | Salary | Allowance |
P01 | Rohit | Manager | 89000 | 4800 |
P02 | Kashish | Clerk | NULL | 1600 |
P03 | Mahesh | Supervisor | 48000 | NULL |
P04 | Salil | Clerk | 31000 | 1900 |
P05 | Ravina | Supervisor | NULL | 2100 |
Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of personals whose allowance is known.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all personals. The column heading ‘Total Salary’ should also be displayed.
(iii) Delete the record of Supervisors who have salary greater than 25000.
Answer:
(i) UPDATE Personal SET Salary=Salary*0.5 WHERE Allowance IS NOT NULL;
(ii) SELECT Name, Salary+Allowance AS “Total Salary” FROM Personal;
(iii) DELETE FROM Personal WHERE Salary>25000
Explanation:
(i) The DML command UPDATE can be used to change or update values in a table. Where clause can be used with it to update records matching a condition.
(ii) Values calculated using existing field values may be displayed in a select query by specifying the expression for it in the query. This is done here by writing “Salary + Allowance”. The column heading in the display can be changed by specifying the new heading with “AS” clause.
(iii) The DML command DELETE is used to remove records from a table. Where clause can be added to delete certain records.
Question 30.
A list, NList contains following record as list elements: [3]
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display “Stack Empty” when there are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A ", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'], ['Dubai', 'UAE'], ['Columbo', 'Sri Lanka'] The output should be: ['Columbo', 'Sri Lanka'] ['Dubai', 'UAE'] ['Naypyidaw', 'Myanmar7] Stack Empty
Answer:
(i)
travel = [] def Push_element(NList): for L in NList: if L[1]! = "India" and L[2]<3500 : , travel.append ([L[0], L[1]])(ii) def Pop_element(): while len(travel): else: print("Stack Empty").
Explanation:
(i) In the function Push_element(), the function receives a nested list of elements of travel data as [City, Country, distance]. It picks each list of journey into L using the for loop. The if condition checks the City which is there in L[1] and “distance ” from L[2], The condition for outside India is checked as “!=India” and the condition for distance is checked as L[2]<3500. Such records are pushed to the stack using the append() function.
(ii) The Pop_element() function loops through the length of the list by using len(travel) and pops the last elements from the list using “travel.pop()”
Section-D
Question 31.
Meticulous EduServe is an educational organization. It is planning to setup its India campus at Chennai with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN, ENGINEERING, BUSINESS and MEDIA. [1 × 5 = 5]
Block to Block distances (in Mtrs.)
From | To | Distance (in Mtrs.) |
ADMIN | ENGINEERING | 55 m |
ADMIN | BUSINESS | 90 m |
ADMIN | MEDIA | 50 m |
ENGINEERING | BUSINESS | 55 m |
ENGINEERING | MEDIA | 50 m |
BUSINESS | MEDIA | 45 m |
DELHI HEAD OFFICE | CHENNAI CAMPUS | 2175 km |
Number of computers in each of the blocks/Centre is as follows:
ADMIN | 110 |
ENGINEERING | 75 |
BUSINESS | 40 |
MEDIA | 12 |
DELHI HEAD | 20 |
(a) Suggest and draw the cable layout to efficiently connect various blocks of buildings within the CHENNAI campus for connecting the digital devices.
(b) Which network device will be used to connect computers in each block to form a local area network?
(c) Which block, in Chennai Campus should be made the server? Justify your answer.
(d) Which fast and very effective wireless transmission medium should preferably be used to connect the head office at DELHI with the campus in CHENNAI?
(e) Suggest a device/software to be installed in the CHENNAI Campus to take care of data security.
Answer:
(a)
Bus Topology—Network topology efficiently connect various blocks of buildings within a campus.
(b) Switch
(c) Admin block, as it has maximum number of computers.
(d) Microwave
(e) Firewall
Explanation:
(a) The least three distances have to be considered, and connected. Here the least three distances are 45m, 50m and 55m. This saves cable costs and brings better connectivity.
(b) A switch is a device that connects multiple computers in a local area network, efficiently.
(c) ADMIN block, as it houses the maximum number of computers
(d) Microwave transmission will be required, as the distance between DELHI and CHENNAI blocks is 2175 KMS. Microwave can travel between cities, states and countries.
(e) A Firewall can filter a private network from malware and security threats.
Question 32.
(i) Differentiate between r+ and w+ file modes in Python. [2+3=5]
(ii) Consider a file, SPORT.DAT, containing records of the following structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as “Basket Ball” to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT.
OR
(Option for Part (ii) only)
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.
Answer:
(i) r+ mode:
- Primary function is reading
- File pointer is at beginning of file
- if the file does not exist, it results in an error w+ mode:
- primary function is writing
- if the file does not exist, it creates a new file.
- If the file exists, previous data is overwritten
- File pointer is at the beginning of file
(ii)
def copyData(): fObj = open("SPORT.DAT", "rb") fObj1 = open("BASKET.DAT", "wb") cnt = 0 try: while True: data = pickle.load(fObj) print(date) if data[0] = "Basket Ball" : pickle.dump(data, fObj1) except: fObj.close() fObj1.close() return cnt
Explanation:
The function copyData() copies certain records from one binary file to another. 1st two statements are opening the source file in “rb” (read) mode and target file in “wb” (write) mode respectively. Each record is read using the load() function into a list “data”. The sportname which is the 1st element of the list – data[0] is checked for “Basket Ball”. In case of a match the record is written into the target file using the dump() function.
OR
def Searchtype(mtype): fObj = open("CINEMA.DAT", "rb") try: while True: data = pickle.load(fObj) if data[2] = mtype: print("Movie Number :", data[0]) print("Movie Name:", data[1]) print("Movie Type:", data[2]) except EOFError: fObj.close()
Explanation:
The code displays details of movie records that match a certain condition from a binary file. ‘The binary file “Cinema.dat” in opened in read mode. Each record is read by the load() function into a list “data”. The movie type is checked with the mtype parameter received. Since movie type is the 3rd field in the list, data[2] is matched with “mtype”. For matching cases the details are printed.
Question 33.
(i) Define the term Domain with respect to RDBMS. Give one example to support your answer. [1+4=5]
(ii) Kabir wants to write a program in Python to insert the following record in the table named Student in MYSQL database, SCHOOL:
- rno(Roll number)- integer
- name(Name) – string
- DOB (Date of birth) – Date
- Fee-float
Note the following to establish connectivity between Python and MySQL:
- Username – root
- Password – tiger
- Host – localhost
The values of fields mo, name, DOB and fee has to be accepted from the user. Help Kabir to write the program in Python.
Answer:
(i) A Domain is the pool of values from which a column derives its values. For example the attribute “state” derives its values from the list of states in a country.
(ii)
import mysql.connector as mysql coni = mysqu.connect(host="localhost", user="root", password="tiger", database="sample2023") mycursor=conl.cursor() rno = int(input("Enter Roll Number ::")) name = input("Enter the name ::") DOB = input("Enter date of birth ::") fee = float(input("Enter Fee ::")) query = "INSERT into student values ({},'{}','{}', {}).format(rno, name, DOB, fee) mycursor.execute(query) conl.commit() print("Data added successfull") conl.close()
Explanation:
- The 1st statement imports the mysql-connector package, as the respective functions for connectivity and operations are present in the package.
- The connect() function is responsible for the connection between front end python application and back end mysql with the parameters -host, database name, user ID and password.
- The data is input next.
- The insert command is used in creating the SQL query string for insertion of the record.
- The execute function executes the SQL command.
- commit() function makes the changes permanent.
Section-E
Question 34.
Consider the tables PRODUCT and BRAND given below: [1 × 4 + 4]
Table: PRODUCT
PCode | PName | UPrice | Rating | BID |
P01 | Shampoo | 120 | 6 | M03 |
P02 | Toothpaste | 54 | 8 | M02 |
P03 | Soap | 25 | 7 | M03 |
P04 | Toothpaste | 65 | 4 | M04 |
P05 | Soap | 38 | 5 | M05 |
P06 | Shampoo | 245 | 6 | M05 |
Table: BRAND
BID | BName |
M02 | Dant Kanti |
M03 | Medimix |
M04 | Pepsodent |
M05 | Dove |
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT and BRAND.
(ii) Display the structure of the table PRODUCT.
(iii) Display the average rating of Medimix and Dove brands
(iv) Display the name, price, and rating of products in descending order of rating.
Answer:
(i) SELECT PName, BName FROM PRODUCT P, BRAND B WHERE P.BID=B.BID;
(ii) DESC PRODUCT;
(iii) SELECT BName, AVG(Rating) FROM PRODUCT P, BRAND B
WHERE P.BID=B.BID GROUP1 BY BName HAVING (BName=’Medimix’ OR BName=’Dove’);
(iv) SELECT PName, UPrice, Rating FROM PRODUCT ORDER BY Rating DESC;
Explanation:
- The query selects the product name and corresponding brand names from both the tables by matching the joining column(BID) – P.BID=B.BID
- Describe is a DDL command that displays the structure of a table.
- The GROUP BY clause is used here to group the records on brand name. The having clause is used to extract only those groups whose Bname is “Medimix” or “Dove”. The joining condition “P.BID=B.BID” is used since records are brought from multiple tables.
- The fields to be displayed – Pname, UPrice and Rating are specified with Select command. As the records are to be displayed in descending order of Rating, The “Order by Rating DeSc ” clause is used.
Question 35.
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 [4]
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.
Answer:
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) CSVWriter.write row(headings) CSVWriter.write rowdata) f.close()
Explanation:
The function Accept() is writing certain data into a csv file. The input() function inputs the data to be added to the file.. The CSV file “Result.csv” is opened in append mode to add records. A list of the data input is created in “data” and list of the column headings is created ini “headings”. The writer() function creates the csv writer object “csvwriter”. The heading and the data input is written to the csv file using writerow() function. The file object is closed by the close() function.