KnowledgeBoat Logo
OPEN IN APP

Sample 2024

Solved 2024 Sample Question Paper CBSE Class 12 Computer Science (083)

Class 12 - CBSE Computer Science Solved Question Papers



Section A (Objective Type Questions 1 Mark Each)

Question 1

State True or False:

"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

Reason — In a Python program, if a break statement is given in a nested loop, it only terminates the execution of the innermost loop where the break statement is encountered. It does not affect the outer loops or any remaining loops in the nested structure.

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. 20, 6
  2. 6, 20
  3. 9, 6
  4. 6, 9

Answer

6, 20

Reason — The datatype VARCHAR(20) is a variable-length character string that can store up to 20 characters. When "Keshav" (6 characters) is assigned to attribute A with VARCHAR(20), it occupies only 6 characters of storage space because VARCHAR adjusts the space based on the actual data length. The datatype CHAR(20) is a fixed-length character string that always occupies the specified amount of space, in this case, 20 characters. When "Meenakshi" (9 characters) is assigned to attribute B with CHAR(20), it still occupies all 20 characters of storage space because CHAR pads the data with spaces to fill up the allocated space, even if the actual data is shorter.

Question 3

What will be the output of the following statement:

print(3 - 2 ** 2 ** 3 + 99/11)

  1. 244
  2. 244.0
  3. -244.0
  4. Error

Answer

-244.0

Reason — In Python, both ** (exponentiation) and / (division) operators have the same level of precedence, which means they are evaluated from left to right if they appear together without parentheses. However, the exponentiation operator ** is right-associative, which means it is evaluated from right to left. In the given expression print(3 - 2 ** 2 ** 3 + 99 / 11), the innermost exponentiation (2 ** 3) is evaluated first, followed by the outer exponentiation (2 ** 8). Then subtracting the result of the exponentiation from 3, 3 − 256 = −253, then adding the result of the division ((99/11) = 9) to the previously calculated value −253 + 9 = −244.0. The expression is evaluated as follows:

3 - 2 ** 2 ** 3 + 99 / 11

= 3 - 2 ** 8 + 99 / 11

= 3 - 256 + 99 / 11

= 3 - 256 + 9.0

= -253 + 9.0

= -244.0

Question 4

Select the correct output of the code:

s = "Python is fun"
l = s.split()
s_new = "-".join([l[0].upper(), l[1], l[2].capitalize()])
print(s_new)
  1. PYTHON-IS-Fun
  2. PYTHON-is-Fun
  3. Python-is-fun
  4. PYTHON-Is -Fun

Answer

PYTHON-is-Fun

Reason — The code initializes a string variable s with the value 'Python is fun'. It splits the string into words using split() method, then converts the first word to uppercase ('PYTHON') using indexing and the upper() method, and capitalizes the third word ('Fun') with the capitalize() method. It then joins the modified words with a hyphen ('-') as the separator using the join() method and prints the result.

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. 5, 3
  2. 8, 15
  3. 3, 5
  4. 15, 8

Answer

8, 15

Reason — When performing a Cartesian product (cross join) of two tables, the resulting table retains all columns from both tables. Therefore, the degree of the Cartesian product is the sum of the degrees of the two tables i.e., Degree of Alpha + Degree of Beta = 5 + 3 = 8. Similarly, the cardinality of the Cartesian product is the total number of rows resulting from the cross join, which is the product of the cardinalities of the two tables, i.e., Cardinality of Alpha * Cardinality of Beta = 3 * 5 = 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. PAN
  2. LAN
  3. MAN
  4. WAN

Answer

PAN

Reason — A personal area network (PAN) is the interconnection of information technology devices within the range of an individual person, typically within 10 meters. Bluetooth technology is used to create PANs for short-range wireless communication between devices. In Riya's case, she is using Bluetooth to connect her mobile phone to her laptop within a range of about 10 meters, forming a PAN (Personal Area Network).

Question 7

Which of the following will delete key-value pair for key = “Red” from a dictionary D1 ?

  1. delete D1("Red")
  2. del D1["Red"]
  3. del.D1["Red"]
  4. D1.del["Red"]

Answer

del D1["Red"]

Reason — The syntax to delete a key-value pair from a dictionary in Python is : del dictionary_name[key]. Therefore, according to this syntax, del D1["Red"] is correct statement."

Question 8

Consider the statements given below and then choose the correct output from the given options:

pride = "#G20 Presidency"
print(pride[-2:2:-2])
  1. ndsr
  2. ceieP0
  3. ceieP
  4. yndsr

Answer

ceieP0

Reason — The code assigns the string "#G20 Presidency" to the variable pride. The slicing operation pride[-2:2:-2] starts from the second last character ("y"), which is at index -2, moves backward by 2 characters at a time due to the step value of -2, and stops before reaching the third character ("G"), which is at index 2. Hence, the output will be 'ceieP0'.

Question 9

Which of the following statement(s) would give an error during execution of the following code ?

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 #Statement 4
  1. Statement 1
  2. Statement 2
  3. Statement 3
  4. Statement 4

Answer

Statement 4

Reason — The statement that would give an error during execution of the given code is Statement 4 (tup[4] = 80). This is because tuples in Python are immutable, meaning we cannot modify the elements of a tuple after it has been created. Here, it is attempting to assign 80 to the element at the index 4 of a tuple, which results in an error because tuples do not support item assignment.

Question 10

What possible outputs(s) will be obtained when the following code is executed?

import random
myNumber = random.randint(0, 3)
COLOR = ["YELLOW", "WHITE", "BLACK", "RED"]
for I in range(1, myNumber):
    print(COLOR[I], end = "*")
    print()
  1. RED*
    WHITE*
    BLACK*
  2. WHITE*
    BLACK*
  3. WHITE* WHITE*
    BLACK* BLACK*
  4. YELLOW*
    WHITE*WHITE*
    BLACK* BLACK* BLACK*

Answer

WHITE*
BLACK*

Reasonrandom.randint(0, 3) will generate a random integer between 0 and 3. Possible outcomes are 0, 1, 2, or 3. Since 0 and 1 would make the loop invalid, we consider 2 and 3.

When myNumber is 2:

The loop for i in range(1, myNumber) will iterate over range(1, 2), which includes only the number 1. The code will print COLOR[1], which is "WHITE", followed by an asterisk (*). So, one of the possible outputs is:
WHITE*

When myNumber is 3:

The loop for i in range(1, myNumber) will iterate over range(1, 3), which includes the numbers 1 and 2. The code will print COLOR[1], which is "WHITE", followed by an asterisk (*), and then move to the next line. Then, it will print COLOR[2], which is "BLACK", followed by an asterisk (*). So, the other possible output is:
WHITE*
BLACK*

Since the output when myNumber is 3 is among the possible outputs, it's the correct answer.

Question 11

Fill in the blank:

The modem at the sender’s computer end acts as a ............... .

  1. Model
  2. Modulator
  3. Demodulator
  4. Convertor

Answer

Modulator

Reason — The modem at the sender's computer end acts as a modulator, which is responsible for converting digital data into analog signals for transmission over the communication channel.

Question 12

Consider the code given below:

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?

  1. global a
  2. global b = 100
  3. global b
  4. global a = 100

Answer

global b

Reason — When we want to modify a global variable within a function in Python, we need to use the global keyword followed by the name of the global variable. In this case, since the variable b is declared as a global variable outside the function, we need to declare it as a global variable again inside the function using global b before attempting to modify its value.

Question 13

State whether the following statement is True or False:

An exception may be raised even if the program is syntactically correct.

Answer

True

Reason — An exception can be raised even if the program is syntactically correct. This can happen due to various runtime errors such as division by zero, accessing an index out of range, trying to perform an operation on incompatible data types, etc. These types of errors are detected during the execution of the program and can lead to exceptions being raised, even if the program's syntax is correct.

Question 14

Which of the following statements is FALSE about keys in a relational database?

  1. Any candidate key is eligible to become a primary key.
  2. A primary key uniquely identifies the tuples in a relation.
  3. A candidate key that is not a primary key is a foreign key.
  4. A foreign key is an attribute whose value is derived from the primary key of another relation.

Answer

A candidate key that is not a primary key is a foreign key.

Reason — A candidate key that is not chosen as the primary key remains a candidate key and is not automatically a foreign key.

Question 15

Fill in the blank:

In case of ............... switching, before a communication starts, a dedicated path is identified between the sender and the receiver.

Answer

circuit

Question 16

Which of the following functions changes the position of file pointer and returns its new position?

  1. flush()
  2. tell()
  3. seek()
  4. offset()

Answer

seek()

Reason — The seek() function in Python is utilised to relocate the file pointer within a file to a specific position. It also accepts an optional second argument, which denotes the starting point for determining this new position.

Question 17

Assertion(A): List is an immutable data type.

Reasoning(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.

  1. Both A and R are true, and R is the correct explanation of A.
  2. Both A and R are true, and R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Assertion is false but Reason is true.

Reason — List is a mutable data type. When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable with the updated value is created, and the variable name is reassigned to point to this new object in memory.

Question 18

Assertion(A): Python Standard Library consists of various modules.

Reasoning(R): A function in a module is used to simplify the code and avoids repetition.

  1. Both A and R are true, and R is the correct explanation of A.
  2. Both A and R are true, and R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both Assertion and Reason are true but Reason is not the correct explanation for Assertion.

Reason — The Python Standard Library is a collection of modules and packages that provide a wide range of functionalities. A function in a module helps to organize code, simplify it, and avoid repetition which makes programming more efficient.

Section B (Very Short Answer Questions 2 Marks Each)

Question 19(a)

(i) Expand the following terms: POP3, URL

(ii) Give one difference between XML and HTML.

Answer

(i) POP3 – Post Office Protocol 3
URL – Uniform Resource Locator

(ii) One difference between XML and HTML:

HTML( Hyper text mark Up language)XML (Extensible Markup Language)
It is a static web development language – only focuses on how data looks. It is used for only displaying data, cannot transport data.It is a dynamic web development language – as it is used for transporting and storing data.

Question 19(b)

(i) Define the term bandwidth with respect to networks.

(ii) How is http different from https ?

Answer

(i) Bandwidth is the maximum rate of data transfer over a given transmission medium or the amount of information that can be transmitted over a network.

(ii) HTTPS (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to encrypt data being transmitted over the Internet. Therefore, HTTPS helps in secure browsing while HTTP does not.

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.

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):  #correction 1
    rev = 0
    rem = 0
    while num > 0: #correction 2
        rem = num % 10  #correction 3
        rev = rev * 10 + rem
        num = num // 10
    return rev  #correction 4
print(revNumber(1234))
Explanation
  1. correction 1 — The correct keyword to define a function is "def" not "define".
  2. correction 2 — Instead of "While" (capital W) in the while loop, it should be "while" (lowercase w).
  3. correction 3 — The comparison operator "==" in the line rem == num % 10 should be replaced with the assignment operator "=".
  4. correction 4 — Moved the "return" statement outside the while loop to return the reversed number after the loop completes.

Question 21(a)

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

Answer

PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Doha"}
def countNow(PLACES):
    for place in PLACES.values():
        if len(place) > 5:
            print(place.upper())
countNow(PLACES)
Output
LONDON  
NEW YORK

Question 21(b)

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

def lenWords(STRING):
    T = ()
    L = STRING.split()
    for word in L:
        length = len(word)
        T = T + (length, )
    return T

Question 22

Predict the output of the following code:

S = "LOST"
L = [10, 21, 33, 4]
D = {}
for I in range(len(S)):
    if I % 2 == 0:
        D[L.pop()] = S[I]
    else:
        D[L.pop()] = I + 3
for K, V in D.items():
    print(K, V, sep = "*")

Answer

Output
4*L
33*4
21*S
10*6
Explanation

The code initializes variables S, L, and D, representing a string, list, and dictionary, respectively. The code iterates through the indices of string S. If the index is even, it assigns the popped element from list L as a key in dictionary D with the corresponding character from S as its value. If the index is odd, it assigns the popped element from L as a key in D with the value being the index plus 3. This process continues until the loop ends. After the loop, it prints each key-value pair from D, with keys and values separated by "*".

Question 23(a)

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.

Answer

(i)

L1.insert(2, 200)

(ii)

message.endswith('.')

Question 23(b)

A list named studentAge stores age of students of a class. Write the Python command to import the required module and (using built-in function) to display the most common age value from the given list.

Answer

import statistics
print(statistics.mode(studentAge))

Question 24(a)

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 EmpId of integer type to the table Employee. Thereafter, write the command to insert the following record in the table:

EmpId - 999
Ename - Shweta
Department: Production
Salary: 26900

Answer

SQL command to add primary key in the table:

ALTER TABLE Employee ADD EmpId INTEGER
PRIMARY KEY ;

SQL command for inserting data will be:

INSERT INTO Employee (EmpId, Ename, Department, Salary)
VALUES (999, "Shweta", "Production", 26900) ;

Question 24(b)

Zack is working in a database named SPORT, in which he has created a table named “Sports” containing columns SportId, SportName, no_of_players, and category. After creating the table, he realized that the attribute, category has to be deleted from the table and a new attribute TypeSport of data type string has to be added. This attribute TypeSport cannot be left blank. Help Zack write the commands to complete both the tasks.

Answer

SQL command to delete the attribute category from the table Sports:

ALTER TABLE Sports
DROP category ;

SQL command to add the attribute TypeSport to the table Sports:

ALTER TABLE Sports
ADD TypeSport char(10) NOT NULL ;

Question 25

Predict the output of the following code:

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 = '###')

Answer

Output
10.0$20
10.0$2.0###
Explanation

The code snippet provided defines a function Changer that takes two parameters P and Q, where Q is assigned a default value of 10. Inside the function, P is divided by Q and P is assigned the quotient, and then Q is assigned the remainder of P divided by Q. The modified P value is returned from the function. In the main code, variables A and B are initialized with values 200 and 20, respectively. The Changer function is called first with A and B as arguments, modifying the value of A. The updated values of A and B are then printed with a separator of '$'. Next, the Changer function is called again with only B as an argument, updating B. Finally, the updated values of A and B are printed again with a separator of '$' and an end marker of '###'.

Section C (Short Answer Questions 3 Marks Each)

Question 26

Predict the output of the Python code given below:

Text1 = "IND-23"
Text2 = ""
I = 0
while I < len(Text1):
    if Text1[I] >= "0" and Text1[I] <= "9":
        Val = int(Text1[I])
        Val = Val + 1
        Text2 = Text2 + str(Val)
    elif Text1[I] >= "A" and Text1[I] <= "Z":
        Text2 = Text2 + (Text1[I + 1])
    else:
        Text2 = Text2 + "*"
    I += 1
print(Text2)

Answer

Output
ND-*34
Explanation

The provided Python code initializes a variable Text1 with the string value "IND-23". Then it initializes an empty string variable Text2 and an index variable I with the value 0. The while loop continues as long as I is less than the length of Text1. Within the loop, each character of Text1 is checked: if it's a digit (0-9), it increments the digit by 1 and appends it to Text2; if it's an uppercase letter (A-Z), it appends the next character in Text1 to Text2; otherwise, it appends an asterisk "*". After processing all characters, the final value of Text2 is printed.

Question 27

Consider the table CLUB given below and write the output of the SQL queries that follow.

CIDCNAMEAGEGENDERSPORTSPAYDOAPP
5246AMRITA35FEMALECHESS9002006-03-27
4687SHYAM37MALECRICKET13002004-04-15
1245MEENA23FEMALEVOLLEYBALL10002007-06-18
1622AMRIT28MALEKARATE10002007-09-05
1256AMINA36FEMALECHESS11002003-08-15
1720MANJU33FEMALEKARATE12502004-04-10
2321VIRAT35MALECRICKET10502005-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

Output

(i)

+------------------------+
| COUNT(DISTINCT SPORTS) |
+------------------------+
|                      4 |
+------------------------+

(ii)

+-------+--------+
| CNAME | SPORTS |
+-------+--------+
| AMINA | CHESS  |
+-------+--------+

(iii)

+-------+-----+------+
| CNAME | AGE | PAY  |
+-------+-----+------+
| AMRIT |  28 | 1000 |
| VIRAT |  35 | 1050 |
+-------+-----+------+

Question 28(a)

Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with the word ‘You’.

Answer

The Alpha.txt file includes following data :

You To be or not to be, that is the question.
You The quick brown fox jumps over the lazy dog.
To infinity and beyond!
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()
test()
Output
You To be or not to be, that is the question.

You The quick brown fox jumps over the lazy dog.

Question 28(b)

Write a function, vowelCount() in Python that counts and displays the number of vowels in the text file named Poem.txt.

Answer

The Poem.txt file includes following data :

The sun sets in the west.
To be successful, one must work hard.
def vowelCount():
    fobj = open("Poem.txt", "r")
    data = str(fobj.read())
    cnt = 0
    for ch in data:
        if ch in "aeiouAEIOU":
            cnt = cnt + 1
    print(cnt)
    fobj.close()
vowelCount()
Output
16

Question 29

Consider the table Personal given below:

Table: Personal

P_IDNameDesigSalaryAllowance
P01RohitManager890004800
P02KashishClerkNULL1600
P03MaheshSuperviser48000NULL
P04SalilClerk310001900
P05RavinaSuperviserNULL2100

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 personals who have salary greater than 25000.

Answer

(i)

UPDATE Personal
SET Salary = 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;

Question 30

A list, NList contains following record as list elements:

[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', 'Myanmar']
Stack Empty

Answer

(i)

NList=[["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka", 3405]]  
travel = []
def Push_element(NList):
    for L in NList:
        if L[1] != "India" and L[2] < 3500:
            travel.append([L[0], L[1]])
    return travel
print(Push_element(NList))

(ii)

travel = ['Naypyidaw', 'Myanmar'], ['Dubai', 'UAE'], ['Columbo', 'Sri Lanka']
def Pop_element():
    while len(travel):
        print(travel.pop())
    else:
        print("Stack Empty")
Pop_element()

Section D (Long Answer Questions 4 Marks Each)

Question 31

Consider the tables PRODUCT and BRAND given below:

Table: PRODUCT

PCodePNameUPriceRatingBID
P01Shampoo1206M03
P02Toothpaste548M02
P03Soap257M03
P04Toothpaste654M04
P05Soap385M05
P06Shampoo2456M05

Table: BRAND

BIDBName
M02Dant Kanti
M03Medimix
M04Pepsodent
M05Dove

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
GROUP BY BName
HAVING BName = 'Medimix' OR 
BName = 'Dove';

(iv)

SELECT PName, UPrice, Rating
FROM PRODUCT
ORDER BY Rating DESC;

Question 32

Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a csv file named Result.csv, to store the results of students in different sports events. The structure of Result.csv is :

[St_Id, St_Name, Game_Name, Result]

Where

St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'.

For efficiently maintaining data of the event, Vedansh wants to write the following user defined functions:

Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should also be added on top of the csv file.

wonCount() – to count the number of students who have won any event.

As a Python expert, help him complete the task.

Answer

Python code to accept records from users :

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.writerow(headings)
    csvwriter.writerow(data)
    f.close()

Python code to count the number of students who have won any event :

def wonCount():
    f = open('Result.csv', 'r')
    csvreader = csv.reader(f, delimiter = ',')
    head = list(csvreader)
    print(head[0])
    for x in head:
        if x[3] == "WON":
            print(x)
    f.close()   

Section E (Source/Case Based Questions 5 Marks Each)

Question 33

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.

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. CBSE 2024 Computer Science Class 12 Sample Question Paper Solved.

Block to Block distances (in Mtrs.)

FromToDistance
ADMINENGINEERING55 m
ADMINBUSINESS90 m
ADMINMEDIA50 m
ENGINEERINGBUSINESS55 m
ENGINEERINGMEDIA50 m
BUSINESSMEDIA45 m
DELHI HEAD OFFICECHENNAI CAMPUS2175 km

Number of computers in each of the blocks/Center is as follows:

block/centerNumber of computers
ADMIN110
ENGINEERING75
BUSINESS40
MEDIA12
DELHI HEAD20

(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) Is there a requirement of a repeater in the given cable layout? Why/ Why not?

Answer

(a) Below diagrams shows the cable layout for connecting CHENNAI campus blocks:

Meticulous EduServe is an educational organization. It is planning to setup its India campus at Chennai with its head office at Delhi. Suggest and draw the cable layout to efficiently connect various blocks of buildings within the CHENNAI campus for connecting the digital devices. CBSE 2024 Computer Science Class 12 Sample Question Paper Solved.

(b) Switch network device will be used to connect computers in each block to form a local area network.

(c) Admin block in chennai Campus should be made the server, as it has maximum number of computers.

(d) Using microwave wireless transmission medium is preferable for connecting the head office in Delhi with the campus in Chennai.

(e) No, a repeater is not required in the given cable layout as the length of transmission medium between any two blocks does not exceed 70m.

Question 34(a)

(i) Differentiate between r+ and w+ file modes in Python.

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

Answer

(i)

r+ modew+ mode
Primary function is reading.Primary function is writing.
If the file does not exist, it results in an error.If the file does not exist, it creates a new file.

(ii)

def copyData():
    fobj = open("SPORT.DATA", "rb")
    fobj1 = open("BASKET.DAT", "wb")
    cnt = 0
    try:
        while True:
            data = pickle.load(fobj)
            print(data)
            if data[0] == "Basket Ball":
                pickle.dump(data, fobj1)
                cnt +=1
    except:
        fobj.close()
        fobj1.close()
    return cnt

Question 34(b)

(i) How are text files different from binary files?

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

Text filesBinary Files
Extension is .txtExtension is .dat
Data is stored in ASCII format that is human readable.Data is stored in binary form (0s and 1s), that is not human readable.

(ii)

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

Question 35(a)

(i) Define the term Domain with respect to RDBMS. Give one example to support your answer.

(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 rno, name, DOB and fee has to be accepted from the user. Help Kabir to write the program in Python.

Answer

(i) Domain is a set of values from which an attribute can take value in each row.
For example, roll no field can have only integer values and so its domain is a set of integer values.

(ii)

import mysql.connector as mysql
con1 = mysql.connect(host = "localhost",
                     user = "root",
                     password = "tiger",
                     database = "SCHOOL")
mycursor = con1.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)
con1.commit()
print("Data added successfully")
con1.close()

Question 35(b)

(i) Give one difference between alternate key and candidate key.

(ii) Sartaj has created a 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

Sartaj, now wants to display the records of students whose fee is more than 5000. Help Sartaj to write the program in Python.

Answer

(i) One difference between alternate key and candidate key:

Alternate KeyCandidate Key
A candidate key is a set of attributes (columns) in a table that uniquely identifies each record or row.An alternate key is a set of attributes (columns) in a table that uniquely identifies each record but is not designated as the primary key.

(ii)

import mysql.connector as mysql
con1 = mysql.connect(host = "localhost",
                     user = "root",
                     password = "tiger",
                     database = "SCHOOL")
mycursor = con1.cursor()
query = "SELECT * FROM student WHERE fee > {}".format(5000)
mycursor.execute(query)
data = mycursor.fetchall()
for rec in data:
    print(rec)
con1.close()
PrevNext