Series JPR_PB/25-26/12/083/SET No.
Subject : Computer Science (083)
Marking Scheme
Q No. Section-A (21 x 1 = 21 Marks)
1 State if the following statement is True or False:
The randrange(1,5) gives values 1 to 4 only while randint(1,5) gives 1 to 5.
True
2 What will be the output of the following
code?
L = ["Data Analytics", "Science Vision", "Artificial Intelligence"]
print(L[1][2] + L[2][11:-7])
a) a b) asion c) iIntel d) VisionIntell
c) iIntel
3 Consider the given expression:
False or False and not True or True
Which of the following will be the correct output of the given expression?
a) True b) False c) None d) No output
True
4 In SQL, which operator is used to check if a value is within a range of values (inclusive)?
a) In b) Between c) Range d) Like
b) Between
5 What will be the output of the following Python
code?
str = "Data Science"
print(str[-2::-3])
a) eiS b) ecaD c) ecS d) eai
b) ecaD
6 Write the output of the following Python
code :
for k in range(2,1, -1):
print(k*'INDIA' + '', sep="@",end="$")
INDIAINDIA$
7 What will be the output of the following Python
statement: print(1*2**3**2/2)
256.0
8 Consider the given SQL Query:
SELECT class, count(studentname) FROM student where AVG(age) > 10
GROUP BY class;
Hemant is executing the query but not getting the correct output. Write the
correction.
SELECT class, COUNT(studentname)
FROM student
GROUP BY class
HAVING AVG(age) > 10;
9 What will be the output of the following Python statement:
try:
value = input("Enter a number") + 100
except ValueError:
print("Value Error occurred!")
except ZeroDivisionError:
print("Division by zero error!")
except Exception:
print("Some other error!")
finally:
print("Program completed!")
a) Value Error occurred! b) Some other error!
c) Value Error occurred! d) Some other error!
Program completed! Program completed!
d) Some other error!
Program completed!
10 What will be the output of the following Python code?
data = {"x": 5, "y": 10, "x": 15}
print(len(data))
print(data["x"])
a) 3 and 5 b) 3 and 15 c) 2 and 15 d) 2 and 5
c) 2 and 15
11 What possible output is expected to be displayed on the screen at the time of
execution of the Python program from the following code?
import random
nums = [10, 20, 30, 40, 50]
low = random.randint(0, 1)
high = random.randint(1, 2)
for i in range(low, high + 1):
print(nums[i], end="#")
a) 10#20# b) 20#30# c) 10# d) 20#
a) 10#20# or c) 10#
12 What will be the output of the following Python
code?
x = 10
print(x, end='&&')
def change():
global x
x = x * 2
print(x, end='@@')
change()
print(x)
a) 10&&20@@10 b) 10&&10@@20 c) 10&&20@@20 d) 20&&20@@10
c) 10&&20@@20
13 Which SQL command DOES NOT affect the Cardinality of an existing relation?
a) Insert b) Delete c) Update d) Drop
c) Update
14 What is the output of the given Python
code?
text = "one-two-three-two-one"
result = text.partition("two")
print(result)
a) ('one-', '-three-', '-one') b) ('one-', 'two', '-three-two-one')
c) (' one-two-three-two-one ') d) Error
b) ('one-', 'two', '-three-two-one')
15 Two relations A and B are joined using a NATURAL JOIN operation.
• Relation A has attributes (RollNo, Name, Class)
• Relation B has attributes (RollNo, Marks, Grade)
What will be the degree of the resulting relation?
a) 3 b) 4 c) 5 d) 6
c) 5
16 In SQL, which of the following commands will delete a table permanently:
a) remove b) del c) drop d) delete
c) drop
17 _____ is a protocol used for communication between a web browser and a web
server to access web pages on the Internet.
a) HTML b) HTTP c) FTP d) PPP
b) HTTP
18 Which of the following statements is correct about using a Gateway and a Router
in a computer network?
a) A router connects multiple networks using similar protocols, while a gateway
connects networks using different protocols.
b) A gateway and a router perform exactly the same function in a network.
c) A router is used only for wireless communication, while a gateway is used for
wired communication.
d) Both gateway and router are used only within a single local network.
a) A router connects multiple networks using similar protocols, while a gateway
connects networks using different protocols.
19 Fill in the blank:
A __________________ is a networking device that connects multiple computers
within a local area network and forwards data only to the device for which it is
intended.
a) Router b) Hub c) Switch d) Gateway
c) Switch
Q20 and Q21 are Assertion(A) and Reason(R) 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.
20 Assertion (A): Modifying one list after assigning it to another using = will also
modify the second list.
Reason (R): In Python, using = to copy a list creates a reference to the same
memory location, not a new independent copy.
a)
21 Assertion (A): A table can have only one candidate key as well as one primary key.
Reason (R): All candidate keys that are not chosen as the primary key are called
alternate keys.
d)
22 Basis Local Variable Global Variable
A variable declared inside a
A variable declared outside all functions
Definition function and accessible only
and accessible throughout the program.
within that function.
Exists only within the function Can be accessed inside and outside all
Scope
where it is defined. functions.
Created when the function is
Lifetime called and destroyed when the Exists as long as the program runs.
function ends.
22 OR
Operator Meaning Function
= Assignment Operator Used to assign a value to a variable.
Used to compare two values for
== Comparison Operator
equality.
Example :
x = 10 # '=' assigns the value 10 to variable x
y=x
print(x == y) # '==' compares x and y for equality
23 In Following code , there are syntax and logical errors. Rewrite the code after
correcting and underlining each correction:
num1 == input("Enter first number: ")
num2 == input("Enter second number: ")
if num1 = num2:
print("Both numbers are equal")
else
print("Numbers are not equal"
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 = num2:
print("Both numbers are equal")
else:
print("Numbers are not equal"
24 I. Write a statement to find the index of the first occurrence of the 10 in a list
named mylist which is [1,10,20,50,10,1].
II. Write a statement to print the elements of list L1 in descending order without
making any change to the list L1.
OR
Write Output:
words = ['Python', 'is', 'fun', 'to', 'learn']
sentence = '-'.join(words)
print(sentence)
print(len(sentence))
I. mylist.index(10)
II. print(sorted(L1, reverse=True))
OR
Python-is-fun-to-learn
22
25 A. Write a function double_element() in Python that accepts a list L and a number
n. If the number n exists in the list, it should be updated to its double value. If it
does not exist, print a message saying "Element not found".
OR
B. Write a Python function add_emplyoee() that accepts a dictionary
company_emplyoee, an employee number, a name and department. The
function should add the employee number as key and name, department as
value to the dictionary. If the employee number already exists, print "Employee
already exists" instead of updating it.
def double_element(L, n):
if n in L:
index = L.index(n)
L[index] = n * 2
print("Updated List:", L)
else:
print("Element not found")
L = [2, 5, 8, 10]
double_element(L, 5)
or
def add_employee(company_employee, emp_no, name, department):
if emp_no in company_employee:
print("Employee already exists")
else:
company_employee[emp_no] = (name, department)
print("Employee added successfully")
26 Predict the output of the Python code given below :
employees = {"Arun": [55000, 5000], "Reema": [72000, 8000], "Vijay":
[48000, 4000], "Tina": [65000, 10000]}
high_earners = [ ]
for name in employees:
pay = employees[name]
total = pay[0] + pay[1]
if total > 70000:
high_earners.append(name)
print(high_earners)
['Reema', 'Tina']
27 A. Write suitable commands to do the following in MySQL.
I. Create a database named CBSE
II. Show schema of table KVS
OR
B. Differentiate between unique and distinct in SQL with a suitable example.
CREATE DATABASE CBSE;
DESCRIBE KVS; / DESC KVS;
OR
Basis UNIQUE DISTINCT
Used with a column constraint Used with the SELECT statement to
Usage
while creating a table. remove duplicate rows in the result.
Ensures that all values in a
Eliminates duplicate rows from the
Purpose column are unique (no
output of a query.
duplicates allowed).
Applied on Column level or table definition. Result set (output of a query).
sql<br>CREATE TABLE
Employee ( EmpID INT sql<br>SELECT DISTINCT Department
Example
UNIQUE, Name VARCHAR(20) FROM Employee;
);
28 A. Define the following terms with respect to computer networks
(i) BANDWIDTH
(ii) MODEM
OR
B.
(i) Expand the following terms: POP3 , PPP
(ii) Differentiate between XML and HTML.
Bandwidth is the maximum amount of data that can be transmitted over a network
channel or communication medium in a given period of time.
It is usually measured in bits per second (bps), kilobits per second (Kbps), or
megabits per second (Mbps).
Example: A 100 Mbps connection can transfer 100 megabits of data per second.
(ii) A Modem (short for Modulator–Demodulator) is a hardware device that
converts digital signals from a computer into analog signals for transmission over
telephone lines, and vice versa.
It enables computers to connect to the Internet using traditional communication
lines.
Example: DSL or cable modems used in homes for Internet access.
OR
(i)
POP3: Post Office Protocol Version 3
PPP: Point-to-Point Protocol
(ii)
XML (Extensible Markup
Basis HTML (HyperText Markup Language)
Language)
Used to store and transport
Purpose Used to display data on web pages
data
Tags User-defined tags allowed Predefined tags only
Focuses on data structure and
Focus Focuses on data presentation
meaning
Case Sensitivity Case-sensitive Not case-sensitive
Example <name>KVS</name> <b>KVS</b>
29 A. Write a Python function that displays the number of lines which contains the
word "Python" in a text file named "ProgLang.txt". Also, give total count of
such lines.
OR
B. Write a Python function that displays the number of times the full stop (.), question
mark(?) or exclamation mark (!) appears in a text file named "story.txt".
def count_python_lines():
count = 0
try:
with open("ProgLang.txt", "r") as file:
lines = file.readlines() # Read all lines into a list
for line in lines:
if "Python" in line:
print(line.strip()) # Display line containing 'Python'
count += 1
print("Total number of lines containing 'Python':", count)
except FileNotFoundError:
print("The file 'ProgLang.txt' does not exist.")
OR
def count_punctuation():
count = 0
try:
with open("story.txt", "r") as file:
lines = file.readlines()
for line in lines:
for ch in line:
if ch in [".", "?", "!"]:
count += 1
print("Total number of '.', '?', and '!' in the file:", count)
except FileNotFoundError:
print("The file 'story.txt' does not exist.")
30
A stack, named ClrStack, contains records of some colors. Each record is
represented as a tuple containing four elements - ColorName, RED, GREEN,
BLUE. ColorName is a string, and RED, GREEN, BLUE are integers. For example,
a record in the stack may be ('Yellow', 237, 250, 68) 3 x 1 Write the following user-
defined functions in Python to perform the specified operations on ClrStack:
(i) push_Clr (ClrStack, new_Clr): This function takes the stack ClrStack and a new
record new_Clr as arguments and pushes this new record onto the stack.
(ii) pop_Clr (ClrStack): This function pops the topmost record from the stack and
returns it. If the stack is already empty, the function should display the message
"Underflow".
(iii) isEmpty (ClrStack): This function checks whether the stack is empty. If the
stack is empty, the function should return True, otherwise the function should
return False.
# (i) Function to push a new color record onto the stack
def push_Clr(ClrStack, new_Clr):
ClrStack.append(new_Clr)
print(new_Clr, "added successfully!")
# (ii) Function to pop the topmost record from the stack
def pop_Clr(ClrStack):
if len(ClrStack) == 0:
print("Underflow")
else:
removed = ClrStack.pop()
print("Popped record:", removed)
return removed
# (iii) Function to check whether the stack is empty
def isEmpty(ClrStack):
return len(ClrStack) == 0
31 Predict the output of the following Python code:
s1 = "CSX-12"
s2 = ""
i = 0
while i < len(s1):
if s1[i] >= '0' and s1[i] <= '9':
Num = int(s1[i])
Num += 2
s2 = s2 + str(Num)
elif s1[i] >= 'A' and s1[i] <= 'Z':
s2 = s2 + s1[i].lower()
else:
s2 = s2 + '#'
i += 1
print(s2)
OR
Predict the output of the following Python code:
rivers = ["Ganga", "Yamuna", "Narmada", "Godavari",
"Brahmaputra", "Kaveri"]
result = []
for river in rivers:
if river[0] in 'GK':
result.append(river[-2:].upper())
print(result)
csx#34
OR
['GA', 'RI']
32 i. SELECT NAME
FROM DOCTOR
WHERE NAME LIKE '%A%' AND EXPERIENCE > 10;
ii. SELECT DEPT, COUNT(*) AS Number_of_Doctors
FROM DOCTOR GROUP BY DEPT;
iii. iii. SELECT NAME FROM DOCTOR ORDER BY NAME ASC;
iv. SELECT * FROM DOCTOR WHERE GENDER = 'F' AND EXPERIENCE < 5;
B.
i.
ii.
iii. 3
iv.
AVG(Experience)
7.5
12.5
11.33
11
9
33 import csv
# Function to add book records
def Add_book():
with open('books.csv', 'a', newline='') as file:
writer = csv.writer(file)
# Get user input
B_id = input("Enter Book ID: ")
B_name = input("Enter Book Name: ")
B_price = float(input("Enter Book Price: "))
# Write the record as a list
writer.writerow([B_id, B_name, B_price])
print("Book record added successfully!\n")
# Function to search and display books with price > 1000
def Search_Book():
try:
with open('books.csv', 'r') as file:
reader = csv.reader(file)
found = False
print("\nBooks with price more than 1000:")
print("--------------------------------")
for row in reader:
if len(row) == 3:
B_id, B_name, B_price = row
if float(B_price) > 1000:
print(f"Book ID: {B_id}, Book Name: {B_name}, Price: {B_price}")
found = True
if not found:
print("No books found with price more than 1000.")
except FileNotFoundError:
print("File not found! Please add some books first.")
# Main Program
while True:
print("\n--- Book Management Menu ---")
print("1. Add Book Record")
print("2. Search Books (Price > 1000)")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
Add_book()
elif choice == '2':
Search_Book()
elif choice == '3':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.")
i.
34 i.SELECT Customer_Name, Hotel_Name FROM BOOKINGS INNER JOIN HOTELS
ON BOOKINGS.H_ID = HOTELS.H_ID;
ii. SELECT Customer_Name FROM BOOKINGS WHERE YEAR(Check_In) =
2023;
iii. SELECT AVG(Star_Rating) AS Average_Rating FROM HOTELS;
iv. SELECT Hotel_Name, City, Star_Rating FROM HOTELS ORDER BY
Star_Rating DESC;
OR
SELECT Hotel_Name FROM HOTELS WHERE City IN ('Delhi', 'Mumbai',
'Kolkata');
35 import mysql.connector
try:
# Establish connection to MySQL database
connection = mysql.connector.connect(
host="localhost",
user="admin_user",
password="warehouse2024",
database="WarehouseDB"
)
if connection.is_connected():
cursor = connection.cursor()
# SQL query to update Quantity
update_query = "UPDATE product_inventory SET Quantity = 91 WHERE Item_code
= 208;"
# Execute query
cursor.execute(update_query)
# Commit changes to database
connection.commit()
print("Quantity updated successfully for Item_code 208.")
except mysql.connector.Error as e:
print(" Error while connecting to MySQL:", e)
finally:
# Close cursor and connection
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection closed.")
36 I. import pickle
def add_book():
# Create a dictionary to store book details
book = {}
book['Book_ID'] = int(input("Enter Book ID: "))
book['Book_Title'] = input("Enter Book Title: ")
book['Author_Name'] = input("Enter Author Name: ")
book['Price'] = float(input("Enter Book Price: "))
# Append the record to a binary file
with open('library.dat', 'ab') as file:
pickle.dump(book, file)
print("Book record added successfully!")
# ---- Main Code ----
add_book()
II.
import pickle
def add_book():
# Create a dictionary to store book details
book = {}
book['Book_ID'] = int(input("Enter Book ID: "))
book['Book_Title'] = input("Enter Book Title: ")
book['Author_Name'] = input("Enter Author Name: ")
book['Price'] = float(input("Enter Book Price: "))
# Append the record to a binary file
with open('library.dat', 'ab') as file:
pickle.dump(book, file)
print("Book record added successfully!")
# ---- Main Code ----
add_book()
37 i. PSYCHIATRY, Because block PSYCHIATRY have maximum number of
Computers.
ii. Switch
iii.
iv. Kk
v. a. ftp
or
b. LAN