0% found this document useful (0 votes)
37 views33 pages

Class 12 - CBSE Computer Science

Solved Sample Questions

Uploaded by

Vikas Sehgal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views33 pages

Class 12 - CBSE Computer Science

Solved Sample Questions

Uploaded by

Vikas Sehgal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

CBSE QP 2024

Section A: 1 Mark Questions

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.

2. Identify the output of the following code snippet:

text = "PYTHONPROGRAM"

text = text.replace('PY', '#')

print(text)

Answer:

3. Which of the following expressions evaluates to False?

(A) not(True) and False


(B) True or False
(C) not(False) or True
(D) True and True

Answer: (A) not(True) and False


Here, not(True) is False, and False and False evaluates to False.

4. What is the output of the following code snippet?

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.

5. What will be the output of the following code snippet?

message = "World Peace"

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.

6. What will be the output of the following code snippet?

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.

7. Which of the following statements will raise an exception?


my_dict = {'apple': 10, 'banana': 20, 'orange': 30}

(A) print(my_dict['apple'])
(B) print(my_dict['apple', 'banana'])
(C) my_dict.get('apple')
(D) my_dict.setdefault('apple', 'fruit')

Answer: (B) print(my_dict['apple', 'banana'])


A dictionary key must be a single value, not a tuple unless explicitly defined.

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)

 key: The key to look for in the dictionary.

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

Explanation of print(my_dict.setdefault('apple', 'fruit'))

1. If 'apple' exists in my_dict:

o The method returns the existing value of the key 'apple'.

o The default_value 'fruit' is ignored.

Page | 4
CBSE QP 2024

2. If 'apple' does not exist in my_dict:

o The method adds the key 'apple' to the dictionary with the value 'fruit'.

o It then returns 'fruit'.

The print() function prints the value returned by setdefault().

Example 1: When 'apple' exists

my_dict = {'apple': 'red', 'banana': 'yellow'}

# Retrieve the value of 'apple'

print(my_dict.setdefault('apple', 'fruit'))

print(my_dict)

Output:

red

{'apple': 'red', 'banana': 'yellow'}

 'apple' already exists in my_dict with the value 'red'.

 setdefault() simply returns 'red' and does not modify the dictionary.

Example 2: When 'apple' does not exist

my_dict = {'banana': 'yellow'}

# Add 'apple' with default value 'fruit'

print(my_dict.setdefault('apple', 'fruit'))

print(my_dict)

Output:

fruit

{'banana': 'yellow', 'apple': 'fruit'}

 Since 'apple' does not exist in my_dict, it is added with the value 'fruit'.

 The method returns 'fruit'.

Summary

print(my_dict.setdefault('apple', 'fruit')):

1. Checks if 'apple' exists in the dictionary.

Page | 5
CBSE QP 2024

2. If it exists, the existing value is returned and printed.

3. If it does not exist, 'apple' is added to the dictionary with the value 'fruit', and 'fruit' is returned and
printed.

Let me know if further clarification is needed!

8. What does the list.remove(x) method do in Python?

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.

file = open("example.txt", "r")

data = file.read(100)

____________________ # Move the file pointer to the beginning of the file

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.

12. What is the output of the following code snippet?

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

Answer: ALTER TABLE

Note:

 The degree of a relation (table) in a database refers to the number of attributes


(columns) in that relation (table).
 In relational database terminology, cardinality refers to the number of rows (or tuples) in a
table.

14. What will be the output of the following SQL query?

SELECT * FROM products WHERE product_name LIKE 'App%';

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:

 CHAR(n) is a fixed-length character datatype in SQL.


 It stores exactly n characters.
 If the input value has fewer characters than the specified length n, SQL automatically pads
the remaining space with spaces (whitespace) to ensure the total length is n.
 If the string to be stored in a CHAR(n) column is greater than the specified length n, the
behavior depends on the database system's settings and behavior. Generally, the string
will be truncated to fit the specified length.

16. Which aggregate function is used to find the cardinality of a table in SQL?

Answer: COUNT()

17. Which protocol is used to transfer files over the Internet?

Answer: FTP (File Transfer Protocol)

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.

Answer: Packet Switching

20. Assertion (A): Positional arguments in Python functions cannot be skipped or reordered.

Reason (R): Positional arguments in Python are identified by their name.

Answer: (C) A is True but R is False.


Positional arguments cannot be skipped or reordered, but they are identified by their position, not
by their name.

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.

Reason (R): HAVING is used to filter rows before grouping.

Answer: (C) A is True but R is False.


WHERE filters rows before grouping, while HAVING filters after grouping.

Note: Refer Annexure-1 for more details

Section B: 2 Mark Questions


22. How is a mutable object different from an immutable object in Python? Identify one
mutable object and one immutable object from the following: (1,2), [1,2], {1:1, 2:2}, '123'.

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:

 Mutable object: [1, 2] or {1:1, 2:2}

 Immutable object: (1, 2) or '123'.

23. Give two examples of each of the following: (I) Arithmetic operators (II) Relational
operators.

(I) Examples of arithmetic operators are + (addition) and * (multiplication).


(II) Examples of relational operators are > (greater than) and <= (less than or equal to).

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

Note: Refer Annexure-2 for more details

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)

for i in range(0, b, 2):

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 The loop executes once, accessing a[0] = 'W'.

o Output: W#

2. When b = 2:
The range is range(0, 2, 2) → [0].

o The loop executes once, accessing a[0] = 'W'.

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#

The minimum value of b is 1, and the maximum value of b is 6.

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

new_tup = (tup[-1],) + tup[1:-1] + (tup[0])

return new_tup

result = swap_first_last((1, 2, 3, 4))

print("Swapped tuple: " result)

Corrected Code:

def swap_first_last(tup): # Added colon

if len(tup) < 2:

return tup # Indented return

new_tup = (tup[-1],) + tup[1:-1] + (tup[0],) # Added comma for tuple

return new_tup

result = swap_first_last((1, 2, 3, 4))

print("Swapped tuple:", result) # Corrected print

Explanation of Corrections:

 Added a colon : after def swap_first_last(tup).

Page | 11
CBSE QP 2024

 Corrected indentation of the return statement.

 Ensured (tup[0],) is recognized as a tuple by adding a comma.

 Adjusted the print statement syntax.

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:

ALTER TABLE MOBILE DROP PRIMARY KEY;

B) The SQL command to make M_ID the Primary Key of the MOBILE table is:

ALTER TABLE MOBILE ADD PRIMARY KEY (M_ID);

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

Section C: 3 Mark Questions


29. Write a Python code to implement the following:

(a) Generate 10 random numbers between 1 and 100.


(b) Append all these random numbers to a list.
(c) Write the list of random numbers to a text file named random.txt.

Answer:

import random

# (a) Generate 10 random numbers

random_numbers = [random.randint(1, 100) for _ in range(10)]

# (b) Append the numbers to a list

numbers_list = random_numbers

# (c) Write the list to a file

with open("random.txt", "w") as file:

for number in numbers_list:

file.write(str(number) + "\n")

30. Consider the following tables:

Table: STUDENT

RollNo Name Age Class

1 Raj 16 10

2 Anil 17 11

3 Priya 18 12

Table: SPORTS

RollNo Sport Achievement

1 Cricket District Level

2 Football State Level

Page | 13
CBSE QP 2024

RollNo Sport Achievement

3 Basketball National Level

Write the SQL queries for the following:


(a) Display all details of students who are above 16 years of age.
(b) Display the names of students who have participated in "Football".
(c) Display the student names along with their sport and achievement.

Answer:

(a)

SELECT * FROM STUDENT WHERE Age > 16;

(b)

SELECT STUDENT.Name

FROM STUDENT, SPORTS

WHERE STUDENT.RollNo = SPORTS.RollNo AND SPORTS.Sport = 'Football';

(c)

SELECT STUDENT.Name, SPORTS.Sport, SPORTS.Achievement

FROM STUDENT, SPORTS

WHERE STUDENT.RollNo = SPORTS.RollNo;

31. Write a Python function add_student that:

 Accepts the student name, roll number, and age as arguments.

 Stores the data in a dictionary.

 Appends this dictionary to a list named students.

 Finally, prints the list.

Answer:

students = [] # Global list to store student records

def add_student(name, roll_no, age):

# Create a dictionary for the student

student = {

Page | 14
CBSE QP 2024

"Name": name,

"Roll Number": roll_no,

"Age": age

# Append the dictionary to the list

students.append(student)

# Adding students to the list

add_student("Raj", 1, 16)

add_student("Anil", 2, 17)

add_student("Priya", 3, 18)

# Printing the student list

print(students)

Output:

[{'Name': 'Raj', 'Roll Number': 1, 'Age': 16},

{'Name': 'Anil', 'Roll Number': 2, 'Age': 17},

{'Name': 'Priya', 'Roll Number': 3, 'Age': 18}]

32. The following is a code snippet:

try:

x = int(input("Enter a number: "))

y = int(input("Enter another number: "))

result = x / y

print("Result:", result)

except ValueError:

print("Invalid input! Please enter an integer.")

except ZeroDivisionError:

print("Division by zero is not allowed.")

Page | 15
CBSE QP 2024

finally:

print("Execution completed.")

Predict the output for the following scenarios:


(a) The user enters 10 and 5.
(b) The user enters ten and 5.
(c) The user enters 10 and 0.

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:

Invalid input! Please enter an integer.

Execution completed.

(c)
If the user enters 10 and 0, the output will be:

Division by zero is not allowed.

Execution completed.

33. Consider the following SQL tables:

Table: EMPLOYEE

EmpID EmpName Department Salary

1 Raj HR 50000

2 Priya IT 60000

3 Anil Finance 55000

4 Sita IT 62000

Write SQL queries for the following:


(a) Display the names of all employees in the IT department.
(b) Display the highest salary from the table.
(c) Display all details of employees whose salary is greater than 55000.

Page | 16
CBSE QP 2024

Answer:

(a)

SELECT EmpName FROM EMPLOYEE WHERE Department = 'IT';

(b)

SELECT MAX(Salary) FROM EMPLOYEE;

(c)

SELECT * FROM EMPLOYEE WHERE Salary > 55000;

Section D: 5 Mark Questions

34. Write a Python program to perform the following operations on a text file named data.txt:

(a) Count the number of lines in the file.


(b) Count the number of words in the file.
(c) Count the number of characters in the file.

Answer:

# Function to count lines, words, and characters in a file

def file_statistics(file_name):

try:

with open(file_name, "r") as file:

content = file.readlines()

# Count lines

line_count = len(content)

# Count words

word_count = sum(len(line.split()) for line in content)

# Count characters

char_count = sum(len(line) for line in content)

Page | 17
CBSE QP 2024

print("Number of lines:", line_count)

print("Number of words:", word_count)

print("Number of characters:", char_count)

except FileNotFoundError:

print("File not found! Please check the file name.")

# Example usage

file_statistics("data.txt")

35. Consider the following SQL tables:

Table: ORDERS

OrderID CustomerName OrderDate OrderAmount

101 Raj 2023-01-01 5000

102 Priya 2023-01-15 10000

103 Sita 2023-02-10 7000

Write SQL queries for the following:


(a) Display all orders placed after 2023-01-10.
(b) Display the names of customers who placed orders of more than 8000.
(c) Display the total order amount of all customers.

Answer:

(a)

SELECT * FROM ORDERS WHERE OrderDate > '2023-01-10';

(b)

SELECT CustomerName FROM ORDERS WHERE OrderAmount > 8000;

(c)

SELECT SUM(OrderAmount) AS TotalAmount FROM ORDERS;

36. Write a Python class BankAccount to perform the following:

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

 Ensure withdrawal does not exceed the available balance.

Answer:

class BankAccount:

def __init__(self, name, account_number, balance=0):

self.name = name

self.account_number = account_number

self.balance = balance

def deposit(self, amount):

self.balance += amount

print(f"Deposited {amount}. Current balance: {self.balance}")

def withdraw(self, amount):

if amount > self.balance:

print("Insufficient balance!")

else:

self.balance -= amount

print(f"Withdrew {amount}. Current balance: {self.balance}")

def display(self):

print(f"Account Holder: {self.name}")

print(f"Account Number: {self.account_number}")

print(f"Balance: {self.balance}")

# Example usage

account = BankAccount("Raj", "12345678", 5000)

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:

(a) Push an element onto the stack.


(b) Pop an element from the stack.
(c) Display the stack contents.

Answer:

class Stack:

def __init__(self):

self.stack = []

def push(self, element):

self.stack.append(element)

print(f"Pushed {element} onto the stack.")

def pop(self):

if not self.stack:

print("Stack is empty!")

else:

print(f"Popped {self.stack.pop()} from the stack.")

def display(self):

print("Stack contents:", self.stack)

# Example usage

s = Stack()

s.push(10)

s.push(20)

s.display()

Page | 20
CBSE QP 2024

s.pop()

s.display()

38. The following is a code snippet:

class Employee:

def __init__(self, name, emp_id, salary):

self.name = name

self.emp_id = emp_id

self.salary = salary

def increment_salary(self, percentage):

self.salary += (self.salary * percentage / 100)

def display(self):

print(f"Name: {self.name}, ID: {self.emp_id}, Salary: {self.salary}")

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

# Create an Employee object

employee = Employee("Raj", 101, 50000)

# Increment salary by 10%

employee.increment_salary(10)

# Display updated details

employee.display()

Output:

Name: Raj, ID: 101, Salary: 55000.0

Page | 21
CBSE QP 2024

Section E: 6 Mark Questions

39. Write a Python program to implement a queue using a list. Perform the following
operations:

(a) Enqueue an element into the queue.


(b) Dequeue an element from the queue.
(c) Display the contents of the queue.

Answer:

class Queue:

def __init__(self):

self.queue = []

def enqueue(self, element):

self.queue.append(element)

print(f"Enqueued {element} into the queue.")

def dequeue(self):

if not self.queue:

print("Queue is empty!")

else:

removed = self.queue.pop(0)

print(f"Dequeued {removed} from the queue.")

def display(self):

print("Queue contents:", self.queue)

# 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:

Enqueued 10 into the queue.

Enqueued 20 into the queue.

Enqueued 30 into the queue.

Queue contents: [10, 20, 30]

Dequeued 10 from the queue.

Queue contents: [20, 30]

40. Consider the following SQL tables:

Table: EMPLOYEES

EmpID Name Department Salary JoiningDate

1 Raj HR 50000 2020-05-01

2 Priya IT 60000 2019-08-15

3 Anil Finance 55000 2021-02-01

4 Sita IT 62000 2018-12-10

Write SQL queries for the following:


(a) Display the names of all employees who joined after 2020-01-01.
(b) Display the total salary paid to employees in the IT department.
(c) Display the names and departments of employees whose salary is greater than the average
salary of all employees.

Answer:

(a)

SELECT Name FROM EMPLOYEES WHERE JoiningDate > '2020-01-01';

(b)

Page | 23
CBSE QP 2024

SELECT SUM(Salary) AS TotalSalary FROM EMPLOYEES WHERE Department = 'IT';

(c)

SELECT Name, Department

FROM EMPLOYEES

WHERE Salary > (SELECT AVG(Salary) FROM EMPLOYEES);

41. Write a Python program to perform the following tasks:

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

# Create a dictionary to store product details

products = {

101: {"Name": "Laptop", "Price": 50000},

102: {"Name": "Smartphone", "Price": 20000},

103: {"Name": "Tablet", "Price": 15000}

# (b) Add a new product to the dictionary

def add_product(product_id, name, price):

products[product_id] = {"Name": name, "Price": price}

print(f"Product {name} added.")

# (c) Delete a product from the dictionary

def delete_product(product_id):

if product_id in products:

removed = products.pop(product_id)

print(f"Product {removed['Name']} deleted.")

Page | 24
CBSE QP 2024

else:

print("Product not found!")

# (d) Display all products

def display_products():

print("Product List:")

for pid, details in products.items():

print(f"ID: {pid}, Name: {details['Name']}, Price: {details['Price']}")

# Example usage

add_product(104, "Headphones", 3000)

delete_product(102)

display_products()

Output:

Product Headphones added.

Product Smartphone deleted.

Product List:

ID: 101, Name: Laptop, Price: 50000

ID: 103, Name: Tablet, Price: 15000

ID: 104, Name: Headphones, Price: 3000

42. Write a Python program to create a class Student with the following features:

 Attributes: Name, Roll Number, Marks in three subjects.

 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:

def __init__(self, name, roll_number, marks):

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

return self.calculate_total() / len(self.marks)

def display(self):

total = self.calculate_total()

percentage = self.calculate_percentage()

print(f"Name: {self.name}")

print(f"Roll Number: {self.roll_number}")

print(f"Total Marks: {total}")

print(f"Percentage: {percentage:.2f}%")

# Example usage

student = Student("Raj", 1, [85, 90, 80])

student.display()

Output:

Name: Raj

Roll Number: 1

Total Marks: 255

Percentage: 85.00%

43. Write an SQL query to create a table LIBRARY with the following structure:

Page | 26
CBSE QP 2024

Column Datatype Constraint

BookID INT Primary Key

Title VARCHAR(100) Not Null

Author VARCHAR(50)

Price DECIMAL(10,2)

PublishedYear YEAR Default Value: 2024

Also, insert the following record into the table:


BookID: 1, Title: "Python Programming", Author: "Guido", Price: 599.99.

Answer:

SQL Query to Create the Table:

CREATE TABLE LIBRARY (

BookID INT PRIMARY KEY,

Title VARCHAR(100) NOT NULL,

Author VARCHAR(50),

Price DECIMAL(10,2),

PublishedYear YEAR DEFAULT 2024

);

SQL Query to Insert the Record:

INSERT INTO LIBRARY (BookID, Title, Author, Price)

VALUES (1, 'Python Programming', 'Guido', 599.99);

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.

Key Differences Between WHERE and HAVING:

1. WHERE: Filters rows before grouping

o The WHERE clause filters rows before the rows are grouped using GROUP BY.

o It operates on individual rows of data in the table.

o WHERE does not work with aggregate functions like SUM(), AVG(), etc., because it
filters rows before aggregation occurs.

Example:

SELECT Department, SUM(Salary)

FROM Employee

WHERE Salary > 50000

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.

2. HAVING: Filters rows after grouping

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:

SELECT Department, SUM(Salary) AS TotalSalary

FROM Employee

GROUP BY Department

Page | 28
CBSE QP 2024

HAVING TotalSalary > 100000;

o Here, HAVING TotalSalary > 100000 filters the grouped results to include only
departments where the total salary exceeds 100000.

Comparison Using an Example:

Table: Employee

EmpID Department Salary

1 HR 60000

2 IT 80000

3 HR 70000

4 IT 90000

5 Finance 50000

Query 1: Using WHERE

SELECT Department, SUM(Salary) AS TotalSalary

FROM Employee

WHERE Salary > 60000

GROUP BY Department;

Result:

Department TotalSalary

IT 170000

HR 70000

 WHERE Salary > 60000 filters rows with Salary ≤ 60000 before grouping.

Query 2: Using HAVING

SELECT Department, SUM(Salary) AS TotalSalary

FROM Employee

GROUP BY Department

Page | 29
CBSE QP 2024

HAVING TotalSalary > 100000;

Result:

Department TotalSalary

IT 170000

 HAVING TotalSalary > 100000 filters rows after grouping, removing departments whose
total salary is ≤ 100000.

Key Points to Remember:

 Use WHERE to filter individual rows before grouping.

 Use HAVING to filter grouped data after grouping.

 WHERE cannot work with aggregate functions like SUM() or AVG(), but HAVING can.

Let me know if further clarification is needed!

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.

Key Differences Between extend() and append():

Feature append() extend()

Adds all elements of an iterable (e.g.,


Purpose Adds a single element to the end of the list.
list, tuple) to the list.

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]

my_list.append([4, 5]) # Appending a list

print(my_list)

Output:

[1, 2, 3, [4, 5]]

 The list [4, 5] is treated as a single element and added to my_list.

Using extend()

my_list = [1, 2, 3]

my_list.extend([4, 5]) # Extending with another list

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.

o Example: Adding a single sub-list to a list.

2. Use extend() if you want to concatenate another iterable (e.g., list, tuple, string) to the list.

o Example: Merging two lists into one.

Comparison Using a String:

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:

[1, 2, 3, 'H', 'e', 'l', 'l', 'o']

 extend() unpacks the string "Hello" into individual characters and adds them to the list.

Summary:

 append() adds the entire object as a single element.

 extend() adds the elements of the iterable individually.

Let me know if you need further clarification!

Page | 32
CBSE QP 2024

Page | 33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy