Class 12 - CBSE Computer Science
Class 12 - CBSE Computer Science
1. State True or False: The Python interpreter handles logical errors during code execution.
Answer: False
Logical errors occur due to faulty logic in the code, and the Python interpreter does not detect or
handle them.
Note: Logical errors are mistakes in the program's logic that cause incorrect or unexpected results.
These errors must be identified and fixed by the programmer through debugging and testing.
text = "PYTHONPROGRAM"
print(text)
Answer:
Page | 1
CBSE QP 2024
country = 'International'
print(country.split("n"))
Answer:
Note: The split("n") function splits the string wherever the letter 'n' appears.
print(message[-2::-2])
Answer:
Page | 2
CBSE QP 2024
Note: The slicing [-2::-2] starts from the second last character ('c') and moves backward, taking
every second character.
tuple1 = (1, 2, 3)
tuple2 = tuple1
tuple1 += (4,)
print(tuple1 == tuple2)
Answer: False
Note: When tuple1 is modified by appending (4,), it creates a new tuple. Thus, tuple1 and tuple2 are
no longer equal.
(A) print(my_dict['apple'])
(B) print(my_dict['apple', 'banana'])
(C) my_dict.get('apple')
(D) my_dict.setdefault('apple', 'fruit')
Page | 3
CBSE QP 2024
IMPORTANT:
The setdefault() method in Python is used to retrieve the value of a key in a dictionary. If the key does not
already exist in the dictionary, it adds the key with a default value and then returns that value.
Syntax
dict.setdefault(key, default_value)
default_value: The value to be set for the key if the key does not already exist.
If the key exists, the default_value is ignored.
Page | 4
CBSE QP 2024
o The method adds the key 'apple' to the dictionary with the value 'fruit'.
print(my_dict.setdefault('apple', 'fruit'))
print(my_dict)
Output:
red
setdefault() simply returns 'red' and does not modify the dictionary.
print(my_dict.setdefault('apple', 'fruit'))
print(my_dict)
Output:
fruit
Since 'apple' does not exist in my_dict, it is added with the value 'fruit'.
Summary
print(my_dict.setdefault('apple', 'fruit')):
Page | 5
CBSE QP 2024
3. If it does not exist, 'apple' is added to the dictionary with the value 'fruit', and 'fruit' is returned and
printed.
Answer: list.remove(x) removes the first occurrence of the value x from the list.
9. How many candidate keys are there in a table with 1 primary key and 2 alternate keys?
Answer: 3
Candidate keys include the primary key and all alternate keys.
10. Fill in the blank: Move the file pointer to the beginning of the file after reading 100 bytes.
data = file.read(100)
next_data = file.read(50)
file.close()
Answer: file.seek(0)
11. State True or False: The finally block in Python is executed only if no exception occurs in
the try block.
Answer: False
The finally block is always executed, regardless of whether an exception occurs or not.
c = 10
def add():
global c
c=c+2
print(c, end='#')
Page | 6
CBSE QP 2024
add()
c = 15
print(c, end='%')
Answer: 12#15%
Note: The global keyword allows the variable c to be modified within the function.
13. Which SQL command is used to change the degree of an existing relation (table)?
Note:
Answer: The query will display all details of products whose names start with "App".
Page | 7
CBSE QP 2024
15. In which datatype are values padded with spaces when the stored value is shorter than the
specified length?
Answer: CHAR
Note:
16. Which aggregate function is used to find the cardinality of a table in SQL?
Answer: COUNT()
18. Which network device is used to connect two networks that use different protocols?
Answer: Gateway
19. Name the switching technique that breaks data into packets for transmission.
20. Assertion (A): Positional arguments in Python functions cannot be skipped or reordered.
Note:
Positional arguments are arguments passed to a function in the order in which they are
defined in the function's parameter list.
Page | 8
CBSE QP 2024
The function assigns values to the parameters based on their position, not their name.
21. Assertion (A): The SELECT command in SQL allows the use of both WHERE and HAVING
clauses.
A mutable object is one whose value can be changed after creation, while an immutable object
cannot be modified once created.
From the given examples:
23. Give two examples of each of the following: (I) Arithmetic operators (II) Relational
operators.
24. If L1=[1,2,3,2,1,2,4,2,...] and L2=[10,20,30,...], then (Answer using built-in functions only):
(I)
A) Write a statement to count the occurrences of 4 in L1.
B) Write a statement to sort the elements of L1 in ascending order.
(II)
A) Write a statement to insert all the elements of L2 at the end of L1.
B) Write a statement to reverse the elements of L2.
Answer:
(I)
A) To count the occurrences of 4 in L1: L1.count(4)
B) To sort the elements of L1 in ascending order: L1.sort()
Page | 9
CBSE QP 2024
(II)
A) To insert all the elements of L2 at the end of L1: L1.extend(L2)
B) To reverse the elements of L2: L2.reverse()
25. Identify the correct output(s) of the following code. Also write the minimum and the
maximum possible values of the variable b.
import random
a = "Wisdom"
b = random.randint(1, 6)
print(a[i], end='#')
Answer:
The variable b is assigned a random integer between 1 and 6 (inclusive). The for loop runs with the
range range(0, b, 2). Let’s calculate the behavior for each value of b from 1 to 6.
1. When b = 1:
The range is range(0, 1, 2) → [0].
o Output: W#
2. When b = 2:
The range is range(0, 2, 2) → [0].
o Output: W#
3. When b = 3:
The range is range(0, 3, 2) → [0, 2].
o The loop executes twice, accessing a[0] = 'W' and a[2] = 's'.
o Output: W#s#
4. When b = 4:
The range is range(0, 4, 2) → [0, 2].
o The loop executes twice, accessing a[0] = 'W' and a[2] = 's'.
o Output: W#s#
Page | 10
CBSE QP 2024
5. When b = 5:
The range is range(0, 5, 2) → [0, 2, 4].
o The loop executes three times, accessing a[0] = 'W', a[2] = 's', and a[4] = 'o'.
o Output: W#s#o#
6. When b = 6:
The range is range(0, 6, 2) → [0, 2, 4].
o The loop executes three times, accessing a[0] = 'W', a[2] = 's', and a[4] = 'o'.
o Output: W#s#o#
26. The code provided below is intended to swap the first and last elements of a given tuple.
However, there are syntax and logical errors in the code. Rewrite it after removing all errors.
Underline all the corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
return new_tup
Corrected Code:
if len(tup) < 2:
return new_tup
Explanation of Corrections:
Page | 11
CBSE QP 2024
27. (I) A) What constraint should be applied on a table column so that duplicate values are not
allowed in that column, but NULL is allowed?
OR
B) What constraint should be applied on a table column so that NULL is not allowed in that
column, but duplicate values are allowed?
(II) A) Write an SQL command to remove the Primary Key constraint from a table, named
MOBILE. M_ID is the primary key of the table.
OR
B) Write an SQL command to make the column M_ID the Primary Key of an already existing
table, named MOBILE.
(I)
A) To allow NULL values but prevent duplicates, apply the UNIQUE constraint.
B) To prevent NULL values but allow duplicates, apply the NOT NULL constraint.
(II)
A) The SQL command to remove the Primary Key from the MOBILE table is:
B) The SQL command to make M_ID the Primary Key of the MOBILE table is:
28. A) List one advantage and one disadvantage of star topology. OR B) Expand the term SMTP.
What is the use of SMTP?
(A)
An advantage of star topology is that it is easy to add or remove devices.
A disadvantage of star topology is that if the central node fails, the entire network stops working.
(B)
SMTP stands for Simple Mail Transfer Protocol.
It is used to send emails over a network.
Page | 12
CBSE QP 2024
Answer:
import random
numbers_list = random_numbers
file.write(str(number) + "\n")
Table: STUDENT
1 Raj 16 10
2 Anil 17 11
3 Priya 18 12
Table: SPORTS
Page | 13
CBSE QP 2024
Answer:
(a)
(b)
SELECT STUDENT.Name
(c)
Answer:
student = {
Page | 14
CBSE QP 2024
"Name": name,
"Age": age
students.append(student)
add_student("Raj", 1, 16)
add_student("Anil", 2, 17)
add_student("Priya", 3, 18)
print(students)
Output:
try:
result = x / y
print("Result:", result)
except ValueError:
except ZeroDivisionError:
Page | 15
CBSE QP 2024
finally:
print("Execution completed.")
Answer:
(a)
If the user enters 10 and 5, the output will be:
Result: 2.0
Execution completed.
(b)
If the user enters ten and 5, the output will be:
Execution completed.
(c)
If the user enters 10 and 0, the output will be:
Execution completed.
Table: EMPLOYEE
1 Raj HR 50000
2 Priya IT 60000
4 Sita IT 62000
Page | 16
CBSE QP 2024
Answer:
(a)
(b)
(c)
34. Write a Python program to perform the following operations on a text file named data.txt:
Answer:
def file_statistics(file_name):
try:
content = file.readlines()
# Count lines
line_count = len(content)
# Count words
# Count characters
Page | 17
CBSE QP 2024
except FileNotFoundError:
# Example usage
file_statistics("data.txt")
Table: ORDERS
Answer:
(a)
(b)
(c)
Create an account with attributes for account holder’s name, account number, and
balance.
Page | 18
CBSE QP 2024
Implement methods to deposit money, withdraw money, and display account details.
Answer:
class BankAccount:
self.name = name
self.account_number = account_number
self.balance = balance
self.balance += amount
print("Insufficient balance!")
else:
self.balance -= amount
def display(self):
print(f"Balance: {self.balance}")
# Example usage
account.deposit(2000)
account.withdraw(1000)
Page | 19
CBSE QP 2024
account.display()
37. Write a Python program to implement a stack using a list. Perform the following
operations:
Answer:
class Stack:
def __init__(self):
self.stack = []
self.stack.append(element)
def pop(self):
if not self.stack:
print("Stack is empty!")
else:
def display(self):
# Example usage
s = Stack()
s.push(10)
s.push(20)
s.display()
Page | 20
CBSE QP 2024
s.pop()
s.display()
class Employee:
self.name = name
self.emp_id = emp_id
self.salary = salary
def display(self):
(a) Create an object of the Employee class for an employee named "Raj", ID 101, and salary 50000.
(b) Increment the salary of the employee by 10%.
(c) Display the updated details of the employee.
Answer:
employee.increment_salary(10)
employee.display()
Output:
Page | 21
CBSE QP 2024
39. Write a Python program to implement a queue using a list. Perform the following
operations:
Answer:
class Queue:
def __init__(self):
self.queue = []
self.queue.append(element)
def dequeue(self):
if not self.queue:
print("Queue is empty!")
else:
removed = self.queue.pop(0)
def display(self):
# Example usage
q = Queue()
q.enqueue(10)
Page | 22
CBSE QP 2024
q.enqueue(20)
q.enqueue(30)
q.display()
q.dequeue()
q.display()
Output:
Table: EMPLOYEES
Answer:
(a)
(b)
Page | 23
CBSE QP 2024
(c)
FROM EMPLOYEES
(a) Create a dictionary to store product details where the key is the product ID and the value is a
dictionary containing product name and price.
(b) Add a new product to the dictionary.
(c) Delete a product from the dictionary.
(d) Display all products in the dictionary.
Answer:
products = {
def delete_product(product_id):
if product_id in products:
removed = products.pop(product_id)
Page | 24
CBSE QP 2024
else:
def display_products():
print("Product List:")
# Example usage
delete_product(102)
display_products()
Output:
Product List:
42. Write a Python program to create a class Student with the following features:
Methods:
(a) A method to calculate and return the total marks.
(b) A method to calculate and return the percentage of marks.
(c) A method to display the student details including the total and percentage.
Answer:
class Student:
Page | 25
CBSE QP 2024
self.name = name
self.roll_number = roll_number
self.marks = marks
def calculate_total(self):
return sum(self.marks)
def calculate_percentage(self):
def display(self):
total = self.calculate_total()
percentage = self.calculate_percentage()
print(f"Name: {self.name}")
print(f"Percentage: {percentage:.2f}%")
# Example usage
student.display()
Output:
Name: Raj
Roll Number: 1
Percentage: 85.00%
43. Write an SQL query to create a table LIBRARY with the following structure:
Page | 26
CBSE QP 2024
Author VARCHAR(50)
Price DECIMAL(10,2)
Answer:
Author VARCHAR(50),
Price DECIMAL(10,2),
);
Page | 27
CBSE QP 2024
Annexure-1
WHERE & HAVING CLAUSE
Explanation:
In SQL, both WHERE and HAVING are used to filter rows in a query. However, they operate at
different stages in the execution of the SQL query, particularly in relation to grouping operations
like GROUP BY.
o The WHERE clause filters rows before the rows are grouped using GROUP BY.
o WHERE does not work with aggregate functions like SUM(), AVG(), etc., because it
filters rows before aggregation occurs.
Example:
FROM Employee
GROUP BY Department;
o Here, WHERE Salary > 50000 filters out rows where the Salary is ≤ 50000 before the
rows are grouped by Department.
o Only rows with Salary > 50000 are considered for the aggregation.
o The HAVING clause filters rows after they are grouped by the GROUP BY clause.
o It operates on grouped data and works with aggregate functions like SUM(), AVG(),
etc.
Example:
FROM Employee
GROUP BY Department
Page | 28
CBSE QP 2024
o Here, HAVING TotalSalary > 100000 filters the grouped results to include only
departments where the total salary exceeds 100000.
Table: Employee
1 HR 60000
2 IT 80000
3 HR 70000
4 IT 90000
5 Finance 50000
FROM Employee
GROUP BY Department;
Result:
Department TotalSalary
IT 170000
HR 70000
WHERE Salary > 60000 filters rows with Salary ≤ 60000 before grouping.
FROM Employee
GROUP BY Department
Page | 29
CBSE QP 2024
Result:
Department TotalSalary
IT 170000
HAVING TotalSalary > 100000 filters rows after grouping, removing departments whose
total salary is ≤ 100000.
WHERE cannot work with aggregate functions like SUM() or AVG(), but HAVING can.
Page | 30
CBSE QP 2024
Annexure-2
Append vs extend FUNCTIONS
In Python, extend() and append() are methods used to add elements to a list, but they behave
differently.
Treats the argument as a single element, Unpacks the iterable and adds its
Effect
even if it’s an iterable. elements to the list.
Return
Returns None. Returns None.
Value
Modifies the list by adding one new Modifies the list by adding multiple
Modification
element. elements.
Examples:
Using append()
my_list = [1, 2, 3]
print(my_list)
Output:
Using extend()
my_list = [1, 2, 3]
print(my_list)
Page | 31
CBSE QP 2024
Output:
[1, 2, 3, 4, 5]
The elements of the list [4, 5] are unpacked and added to my_list individually.
When to Use:
1. Use append() if you want to add a single element (even if it’s a list or tuple) to the list.
2. Use extend() if you want to concatenate another iterable (e.g., list, tuple, string) to the list.
With append():
my_list = [1, 2, 3]
my_list.append("Hello")
print(my_list)
Output:
[1, 2, 3, 'Hello']
With extend():
my_list = [1, 2, 3]
my_list.extend("Hello")
print(my_list)
Output:
extend() unpacks the string "Hello" into individual characters and adds them to the list.
Summary:
Page | 32
CBSE QP 2024
Page | 33