0% found this document useful (0 votes)
129 views73 pages

Class 12 CS PYQs Compilation of Full Syllabus PDF by Nitin Paliwal

The document is a study material for Class 12 Computer Science by Nitin Paliwal, focusing on Python programming and CBSE previous years' questions with solutions. It includes various types of questions such as true/false, expression evaluations, and output-based questions, along with explanations for each answer. The material aims to help students prepare for their exams by providing a comprehensive overview of key concepts and problem-solving techniques in Python.

Uploaded by

yaswanth270308
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)
129 views73 pages

Class 12 CS PYQs Compilation of Full Syllabus PDF by Nitin Paliwal

The document is a study material for Class 12 Computer Science by Nitin Paliwal, focusing on Python programming and CBSE previous years' questions with solutions. It includes various types of questions such as true/false, expression evaluations, and output-based questions, along with explanations for each answer. The material aims to help students prepare for their exams by providing a comprehensive overview of key concepts and problem-solving techniques in Python.

Uploaded by

yaswanth270308
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/ 73

#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

CLASS 12
COMPUTER SCIENCE

CBSE PREVIOUS YEARS


QUESTIONS
COMPILATION(2023,
2024, SQP 2025) WITH
SOLUTIONS
(CHAPTERWISE)

By Nitin Paliwal (YOUTUBE)


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

PYTHON REVISION TOUR

1 MARKER QUESTIONS

True/False Type Questions


Ques. 1 State True or False. (CBSE 2023)
“Identifiers are names used to identify a variable, function in a program”.
Answer: True
Explanation: In programming, identifiers are the names given to variables,
functions, classes, etc., to uniquely identify them.

Expression Evaluation
Ques. 2 Consider the given expression: (CBSE 2023)
5<10 and 12>7 or not 7>4
Step-by-step evaluation:
 5 < 10 is True
 12 > 7 is True
o So, True and True gives True
 7 > 4 is True, hence not 7 > 4 is False
 Finally, True or False evaluates to True
Answer: True

Ques. 3 What will be the following expression to be evaluated in Python?


(CBSE 2023)
print(4+3*5/3-5%2)
(a) 8.5
(b) 8.0
(c) 10.2
(d) 10.0
Step-by-step evaluation (following Python operator precedence):
1. Multiplication and Division:
o 3 * 5 = 15
o 15 / 3 = 5.0
2. Modulus Operation:
o 5%2=1
3. Addition and Subtraction:
o 4 + 5.0 = 9.0
o 9.0 - 1 = 8.0
Answer: 8.0
(Correct option: b)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 4 What will be the output of the following statement: (CBSE 2024)
print(16*5/4*2/5-8)
Step-by-step evaluation:
1. Multiplication and Division (from left to right):
o 16 * 5 = 80
o 80 / 4 = 20.0
o 20.0 * 2 = 40.0
o 40.0 / 5 = 8.0
2. Subtraction:
o 8.0 - 8 = 0.0
Answer: 0.0

Ques. 5 Which of the following expressions evaluates to False? (CBSE 2025)


(a) not(True) and False
(b) True or False
(c) not(False and True)
(d) True and not(False)
Step-by-step evaluation:
 Option (a):
o not(True) → False
o False and False → False
 Option (b): True or False → True
 Option (c):
o False and True → False
o not(False) → True
 Option (d):
o not(False) → True
o True and True → True
Only option (a) evaluates to False.

Valid Identifier/keyword
Ques. 6 Which of the following is a valid keyword in Python? (CBSE 2023)
(a) false
(b) return
(c) non_local
(d) none
Answer: (b) return
Explanation:
 false is not a Python keyword (the Boolean literal is False with an
uppercase "F").
 non_local is not valid; the actual keyword is nonlocal (without the
underscore).
 none is not a Python keyword (the literal is None with an uppercase "N").
Thus, only return is a valid keyword.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Invalid/Error Causing/Exception Statements


Ques. 7 Which of the following statement(s) would give an error after executing
the following code? (CBSE 2023)
Stud={"Murugan": 100, "Mithu":95)} # Statement 1
print (Stud[95]) #Statement 2
Stud ["Murugan"]=99 #Statement 3
print (Stud.pop()) #Statement 4
print (Stud) #Statement 5

(a) Statement 2
(b) Statement 3
(c) Statement 4
(d) Statements 2 and 4
Answer: (d) Statements 2 and 4
Explanation:
 Statement 1: To create a dictionary
 Statement 2: print(Stud[95]) attempts to access the key 95, which does not
exist. This raises a KeyError.
 Statement 3: Stud["Murugan"] = 99 correctly updates the value for the key
"Murugan", so it is valid.
 Statement 4: print(Stud.pop()) is incorrect because the pop() method for
dictionaries requires a key argument. Without it, a TypeError is raised.
 Statement 5: print(Stud) would execute without error.
Thus, Statements 2 and 4 cause errors.

Ques. 8 Identify the invalid Python statement from the following: (CBSE 2024)
(a) d = dict( )
(b) e = { }
(c) f = [ ]
(d) g = dict{ }
Answer: (d) g = dict{ }
Explanation:
 The correct way to create a dictionary is either by using dict() or using
curly braces { }.
 In option (d), the syntax dict{ } is incorrect and will cause a SyntaxError.

Ques. 9 Identify the statement from the following which will raise an error:
(CBSE 2024)
(a) print("A"*3)
(b) print (5*3)
(c) print("15" + 3)
(d) print("15" + "13")
Answer: (c) print("15" + 3)
Explanation:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

 Option (a) repeats the string "A" three times (prints "AAA").
 Option (b) multiplies two integers (prints 15).
 Option (c) attempts to add a string and an integer, which is not allowed
and raises a TypeError.
 Option (d) concatenates two strings (prints "1513").

Ques. 10 If my_dict is a dictionary as defined below, then which of the following


statements will raise an exception? (SQP 2025)

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

(a) my_dict.get('orange')
(b) print(my_dict['apple', 'banana'])
(c) my_dict['apple']=20
(d) print(str(my_dict))
Answer: (b) print(my_dict['apple', 'banana'])
Explanation:
 Option (a): my_dict.get('orange') returns the value 30, so it is valid.
 Option (b): my_dict['apple', 'banana'] attempts to access a key that is the
tuple ('apple', 'banana'), which does not exist in the dictionary, raising a
KeyError.
 Option (c): Updating the value for an existing key is valid.
 Option (d): Converting the dictionary to a string is valid.

Output Based Questions


Ques. 11 Consider the statements given below and then choose the correct
output from the given options: (CBSE 2024)

myStr="MISSISSIPPI"

print(myStr[:4]+"#"+myStr[-5:])

(a) MISSI#SIPPI
(b) MISS#SIPPI
(c) MISS#IPPIS
(d) MISSI#IPPIS
Step-by-step evaluation:
 myStr[:4] slices the string from index 0 to 3. For "MISSISSIPPI", indices
0–3 give "MISS".
 myStr[-5:] takes the last 5 characters. In "MISSISSIPPI" (11 characters),
index -5 corresponds to index 6. The substring from index 6 to the end is
"SIPPI".
 Concatenating these parts with "#" gives "MISS" + "#" + "SIPPI" =
"MISS#SIPPI".
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Correct option: (b) MISS#SIPPI

Ques. 12 What will be the output of the following code snippet? (SQP 2025)
message= “World Peace”
print(message[-2: :-2])
Step-by-step evaluation:
 message[-2] refers to the second last character. For "World Peace", index -
2 is "c" (since index 10 is "e" and index 9 is "c").
 With the slicing [-2: :-2], the slice starts at index 9 and goes backwards in
steps of 2.
o Starting at index 9: "c"
o Next, index 9 – 2 = 7: "e"
o Next, index 7 – 2 = 5: " " (space)
o Next, index 5 – 2 = 3: "l"
o Next, index 3 – 2 = 1: "o"
 Concatenating these characters produces: "c" + "e" + " " + "l" + "o" = "ce lo".
Output: ce lo

Ques. 13 What will be the output of the following code? (SQP 2025)
tuple1 = (1,2,3)
tuple2 = tuple1
tuple1+= (4, )
print(tuple1= =tuple2)
(a) True
(b) False
(c) tuple1
(d) Error
Explanation:
 tuple1 is initially (1, 2, 3), and tuple2 is set to the same tuple.
 The operation tuple1 += (4, ) creates a new tuple (1, 2, 3, 4) and reassigns
it to tuple1 (since tuples are immutable, they cannot be modified in place).
 Now, tuple1 is (1, 2, 3, 4) while tuple2 remains (1, 2, 3).
 Therefore, comparing them with == yields False.
Correct option: (b) False

Ques. 14 Which of the following operators will return either True or False?
(CBSE 2023)
(a) +=
(b) !=
(c) =
(d) *=
Explanation:
 += and *= are assignment operators, and = is the assignment operator;
none of these return a boolean value.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

 != is a comparison operator that checks for inequality and returns either


True or False.
Correct option: (b) !=

FUNCTIONS

1 MARKER QUESTIONS

True/False Questions
Ques. 1 State True or False. (CBSE 2024)
“While defining a function in Python, the positional parameters in the function
header must always be written after the default parameters”.
Answer: False
Explanation:
In Python, parameters with default values (default parameters) must be placed
after those without default values (positional parameters). In other words, you
cannot have a positional (non-default) parameter following a default parameter.

Fill in the blanks


Ques. 2 _______ function is used to arrange the elements of a list in ascending
order. (CBSE 2023)
(a) sort()
(b) arrange()
(c) ascending()
(d) assort()
Answer: (a) sort()
Explanation:
The sort() function/method is used to sort the elements of a list in ascending
order by default.

Direct Function Based Questions

Ques. 3 Which function returns the sum of all elements of a list ? (CBSE 2023)
(a) count()
(b) sum()
(c) total()
(d) add()
Answer: (b) sum()
Explanation:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Python provides the built-in function sum() to compute the sum of all elements in
an iterable, such as a list.

Ques. 4 fetchall() method fetches all rows in a result set and returns a:
(CBSE 2023)
(a) Tuple of lists
(b) List of tuples
(c) List of strings
(d) Tuple of strings
Answer: (b) List of tuples
Explanation:
In Python’s DB API (e.g., with sqlite3), the fetchall() method returns all rows as
a list where each row is represented as a tuple

Ques. 5 What does the list.remove(x) method do in Python? (SQP 2025)

(a) Removes the element at index x from the list


(b) Removes the first occurrence of value x from the list
(c) Removes all occurrences of value x from the list
(d) Removes the last occurrence of value x from the list
Answer: (b) Removes the first occurrence of value x from the list
Explanation:
The remove(x) method searches for the first element in the list whose value is
equal to x and removes it. If x is not found, it raises a ValueError.

Invalid/Error Causing Statements

Ques. 6 Given the following Tuple Tup= (10, 20, 30, 50)
Which of the following statements will result in an error ? (CBSE 2023)

(a) print(Tup[0])
(b) Tup.insert (2,3)
(c) print (Tup[1:2])
(d) print(len(Tup))
Answer: (b) Tup.insert(2,3)
Explanation:
Tuples in Python are immutable, meaning you cannot change their content.
Hence, calling a method like insert() on a tuple will cause an error.

Output Based Question

Ques. 7 Select the correct output of the code : (CBSE 2023)


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

S= "Amrit Mahotsav @ 75"


A=S.partition (" ")
print (a)
(a) ( 'Amrit Mahotsav', '@','75')
(b) ['Amrit','Mahotsav','@','75']
(c) ('Amrit', 'Mahotsav @ 75')
(d) ('Amrit', '', 'Mahotsav @ 75')
Answer: (d) ('Amrit', '', 'Mahotsav @ 75')
Explanation:
The partition(" ") method splits the string at the first occurrence of the space. It
returns a 3-tuple:
 The part before the separator: "Amrit"
 The separator itself: " "
 The part after the separator: "Mahotsav @ 75"
Although the expected tuple is actually ("Amrit", " ", "Mahotsav @ 75"),
option (d) is the closest match (the space may appear visually as an empty
gap). Also, note that the variable name in the print statement should be A
(not a) to avoid a NameError. It appears to be a typographical error in the
question.

Ques. 8 What possible output from the given options is expected to be displayed
when the following Python Code is Executed? (CBSE 2024)
import random
Signal=[‘Red’ , ’Yellow’ , ’Green” ]
for K in range ( 2 , 0 , -1 ):
R=random.randrange(K)
print(Signal[R], end = ’#’)

(a) YELLOW # RED #


(b) RED # GREEN #
(c) GREEN # RED #
(d) YELLOW # GREEN #
Answer: (a) YELLOW # RED #
Explanation:
The loop runs for K = 2 and then K = 1.
 When K = 2: random.randrange(2) returns either 0 or 1. If it returns 1,
then Signal[1] is 'Yellow'.
 When K = 1: random.randrange(1) always returns 0, so Signal[0] is 'Red'.
Thus, one possible output is "Yellow#Red#". (The case difference in the
option is acceptable.)
Ques. 9 Select the correct output of the following code: (CBSE 2024)

event="G20 Presidency@2023"
L=event.split(' ')
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

print(L[::-2])

(a) 'G20'
(b) ['Presidency@2023']
(c) ['G20']
(d) 'Presidency@2023'
Answer: (b) ['Presidency@2023']
Explanation:
 event.split(' ') results in ['G20', 'Presidency@2023'].
 The slice [::-2] starts from the end and picks every second element. For a
2-element list, this gives ['Presidency@2023'].

Ques. 10 Observe the given Python code carefully : (CBSE 2024)

a=20
def convert(a):
b=20
a=a+b

convert(10)
print(a)

Select the correct output from the given options:


(a) 10
(b) 20
(c) 30
(d) Error
Answer: (b) 20
Explanation:
The function convert() works with a local copy of a and does not affect the global
variable a which remains 20.

Ques. 11 What will be the output of the following code? (SQP 2025)

c = 10
def add():
global c
c=c+2
print(c, end='#')

add()
c=15
print(c,end='%')
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(a) 12%15#
(b) 15#12%
(c) 12#15%
(d) 12%15#
Answer: (c) 12#15%
Explanation:
Note: Although the code uses C = 10 (uppercase) and then global c (lowercase),
we assume this is a typographical error and that both refer to the same variable.
 Initially, assume c is 10. In add(), c = c + 2 updates c to 12 and prints 12#.
 Then c is reassigned as 15 and printed with %, yielding 15%.
Thus, the output is 12#15%.

Ques. 12 Identify the output of the following code snippet: (SQP 2025)

text = "PYTHONPROGRAM"
text=text.replace('PY','#')
print(text)

(a) #THONPROGRAM
(b) ##THON#ROGRAM
(c) #THON#ROGRAM
(d) #YTHON#ROGRAM
Answer: (a) #THONPROGRAM
Explanation:
The replace() method substitutes the first occurrence of 'PY' (at the beginning)
with '#'. Hence, "PYTHONPROGRAM" becomes "#THONPROGRAM".

Ques. 13 What is the output of the expression? (SQP 2025)

country='International'
print (country.split("n"))

(a) ('I', 'ter', 'atio', 'al')


(b) ['1', 'ter', 'atio', 'al']
(c) ['I', 'n', 'ter', 'n', 'atio', 'n', 'al']
(d) Error
Answer: (b) ['I', 'ter', 'atio', 'al']
Explanation:
Splitting "International" on "n" (lowercase) gives these segments:
 Before the first n: "I"
 Between the first and second n: "ter"
 Between the second and third n: "atio"
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

 After the third n: "al"


Although Python’s split() returns a list (i.e. ['I', 'ter', 'atio', 'al']), option (b)
correctly represents the sequence of split segments.

Assertion Reason Questions

Ques. 14 (CBSE 2023)


Assertion (A): To use a function from a particular module, we need to import the
module.

Reason (R): import statement can be written anywhere in the program. before
using a function from that module.
Answer:
Both the assertion and the reason are true, and the reason is a correct
explanation for the assertion.
Explanation:
A module must be imported before its functions can be used. Although it is
conventional to write import statements at the top of the program, they can be
placed anywhere—as long as the module is imported before the function is called.

Ques. 15 (CBSE 2024)


Assertion (A) : The expression "HELLO".sort() in Python will give an error.
Reason (R): sort() does not exist as a method/function for strings in Python.
Answer:
Both the assertion and the reason are true, and the reason is the correct
explanation for the assertion.
Explanation:
Strings in Python are immutable and do not have a sort() method; hence, trying
to call "HELLO".sort() will result in an AttributeError.

Ques. 16 (SQP 2025)


Assertion (A): Positional arguments in Python functions must be passed in the
exact order in which they are defined in the function signature.

Reasoning (R): This is because Python functions automatically assign default


values to positional arguments.
Answer:
The assertion is true but the reason is false.
Explanation:
Positional arguments are assigned based on their order in the function call, but
this behavior is not due to any automatic assignment of default values. Default
values are only used when an argument is missing; the requirement to pass
positional arguments in order is simply how argument passing works in Python.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

2 MARKER QUESTIONS

Rewrite the Code Questions

Ques. 17 Atharva is a Python programmer working on a program to find and


return the maximum value from the list. The code written below has syntactical
errors. Rewrite the correct code and underline the corrections made.
(CBSE 2023)

def max_num (L):


max=L(0)
for a in L:
if a > max
max=a
return max
Corrected Code:
def max_num(L):
max=L[0] #use square brackets
for a in L:
if a>max:
max=a #colon after condition
return max

Ques. 18 The code given below accepts five numbers and displays whether they
are even or odd:
Observe the following code carefully and rewrite it after removing all syntax and
logical errors:
Underline all the corrections made. (CBSE 2024)

def EvenOdd()
for i in range(5):
num=int(input("Enter a number")
if num/2==0:
print("Even")
else:
print("Odd")
EvenOdd ()
Corrected Code:
def EvenOdd(): # Added colon after function header
for i in range(5):
num = int(input("Enter a number")) #Added missing closing parenthesis
if num % 2 == 0: #Replaced "num/2==0" with "num % 2 == 0" to
check evenness
print("Even")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

else:
print("Odd")
EvenOdd() #Removed extra space in the function call

Ques. 19 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.
(SQP 2025)

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 after function header
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0],) #Ensured tuple elements have
commas
return new_tup

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


print("Swapped tuple:", result) #Fixed the print statement syntax

Output Based Question

Ques. 20 Write the output of the code given below : (CBSE 2023)

a =30
def call (x) :
global a
if a%2==0:
x+=a
else:
x-=a
return x
x=20

print(call(35),end="#")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

print(call (40),end= "@")


Step-by-Step Execution:
1. Initial Values:
o a = 30 (Even)
o x = 20
2. First Function Call → call(35)
o Since a % 2 == 0 (i.e., 30 is even), x += a
o x = 35 + 30 = 65
o Output: 65#
3. Second Function Call → call(40)
o Again, a % 2 == 0, so x += a
o x = 40 + 30 = 70
o Output: 70@

Final Output: 65#70@

Ques. 21 Predict the output of the code given below : (CBSE 2023)

def makenew (mystr):


newstr=""
count=0
for i in mystr:
if count%2!=0:
newstr=newstr+str(count)
else:
if i.lower():
newstr=newstr+i.upper()
else:
newstr=newstr+i

count+=1
print (newstr)
makenew ("No@1")
Output:
N1@3
Explanation:
 Index 0: 'N' (even index) → 'N' is alphabetic so append its uppercase
(remains "N").
 Index 1: 'o' (odd index) → append the index "1" → becomes "N1".
 Index 2: '@' (even index) → not alphabetic so append "@" → becomes
"N1@".
 Index 3: '1' (odd index) → append the index "3" → final string "N1@3".
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 22 What possible output(s) are expected to be displayed on screen at the


time of execution of the following program : (CBSE 2023)

import random
M=[5,10,15,20,25,30]
for i in range(1,3):
first=random.randint(2,5)- 1
sec=random.randint(3,6)-2
third=random.randint(1,4)
print(M[first],M[sec],M[third], sep="#")

(i)
10#25#15
20#25#25

(ii)
5#25#20
25#20#15

(iii)
30#20#20
20#25#25

(iv)
10#15#25#
20#25#25#

Analysis:
1. List M: Contains six elements: [5, 10, 15, 20, 25, 30]
2. Loop: The for loop runs twice (range(1, 3) produces [1, 2]).
3. Variable first:
o random.randint(2, 5) generates a random integer between 2 and 5
(inclusive).
o Subtracting 1 shifts the range to 1 through 4.
o Thus, first can be 1, 2, 3, or 4.
4. Variable sec:
o random.randint(3, 6) generates a random integer between 3 and 6
(inclusive).
o Subtracting 2 shifts the range to 1 through 4.
o Thus, sec can be 1, 2, 3, or 4.
5. Variable third:
o random.randint(1, 4) generates a random integer between 1 and 4
(inclusive).
o Thus, third can be 1, 2, 3, or 4.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

6. Indexing into M:
o M[first], M[sec], and M[third] access elements at indices first, sec,
and third of list M.
o Given the possible values of first, sec, and third, the accessed
elements can be:
 M[1] = 10
 M[2] = 15
 M[3] = 20
 M[4] = 25
7. Output:
o Each iteration prints three elements from M, separated by #.
o Possible outputs for each iteration include combinations of 10, 15,
20, and 25.
o Since the loop runs twice, the program produces two lines of output.
Evaluating Options:
(i)
10#25#15
20#25#25
 Possible: Yes.
(ii)
5#25#20
25#20#15
 Not possible: M[first] cannot be 5, as first ranges from 1 to 4.
(iii)
30#20#20
20#25#25
 Not possible: M[first] cannot be 30, as first ranges from 1 to 4.
(iv)
10#15#25#
20#25#25#
 Not possible: Each line should contain exactly two # separators. The
trailing # suggests an extra separator.

Conclusion:
Among the provided options, only option (i) is a valid possible output of the
program.

Ques. 23 Predict the output of the following code: (CBSE 2024)

def callon (b=20,a=10):


b=b+a
a=b-a
print(b, "#",a)
return b
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

x=100
y=200
x=callon (x,y)
print(x, "@",y)
y=callon (y)
print(x,"@",y)

Output:
300 # 100
300 @ 200
210 # 200
300 @ 210
Explanation:
1. First call: callon(100, 200)
o b = 100 + 200 = 300
o a = 300 - 200 = 100
o The function prints "300 # 100" and returns 300, which is then
assigned to x.
2. Print statement: Prints "300 @ 200" since x is now 300 and y remains 200.
3. Second call: callon(200)
o Here, b = 200 and a takes its default value 10.
o b = 200 + 10 = 210
o a = 210 - 10 = 200
o The function prints "210 # 200" and returns 210, which is then
assigned to y.
4. Final print: Prints "300 @ 210" with x = 300 and y = 210.

Ques. 24 Identify the correct output(s) of the following code. Also write the
minimum and the maximum possible values of the variable b. ((SQP 2025)

import random
a="Wisdom"
b=random.randint(1,6)
for i in range(0,b,2):
print(a[i],end='#')

(a) W#
(b) W#i#
(c) W#s#
(d) W#i#s#

Step 1: Determining the value of b


 The statement b = random.randint(1, 6) means that b can take any integer
value between 1 (minimum) and 6 (maximum).
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Step 2: How the loop works


 The loop is for i in range(0, b, 2), so i takes values starting at 0 and
increments by 2 until it reaches a value that is not less than b.
 The string a is "Wisdom", with indices:
o 0 → 'W'
o 1 → 'i'
o 2 → 's'
o 3 → 'd'
o 4 → 'o'
o 5 → 'm'
Step 3: Possible outcomes based on different values of b
 If b = 1 or 2:
o range(0, b, 2) produces only 0.
o The output is: a[0] → 'W' followed by #, so "W#".
 If b = 3 or 4:
o range(0, b, 2) produces 0 and 2.
o The output is: a[0] and a[2] → 'W' and 's', so "W#s#".
 If b = 5 or 6:
o range(0, b, 2) produces 0, 2, 4.
o The output is: a[0], a[2], and a[4] → 'W', 's', and 'o', so "W#s#o#".
Step 4: Matching with the given options
The provided options are:
 (a) W#
 (b) W#i#
 (c) W#s#
 (d) W#i#s#
Comparing these with our analysis:
 "W#" is produced when b = 1 or 2 → Option (a) is possible.
 "W#s#" is produced when b = 3 or 4 → Option (c) is possible.
 "W#s#o#" (which would be produced when b = 5 or 6) is not among the
provided options.
 Options (b) and (d) involve printing index 1 ('i') which will never occur
because the loop increments by 2 (starting at index 0).
Final Answer for Ques. 24:
 Possible Outputs:
o (a) W# (when b is 1 or 2)
o (c) W#s# (when b is 3 or 4)
 Minimum value of b: 1
 Maximum value of b: 6
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Miscellaneous Questions

Ques. 25 If L1=[1,2,3,2,1,2,4,2,...], and L2=[10,20,30,..], then (Answer using


builtin functions only)

A) Write a statement to count the occurrences of 4 in L1. OR


B) Write a statement to sort the elements of list L1 in ascending order.
Answer (A):
L1.count(4)
Answer (B):
L1.sort()
Explanation:
 The built-in method count() returns the number of occurrences of a
specified value in the list.
 The built-in method sort() sorts the list in ascending order in place.

Write User-defined Function

Ques. 26 Write a user defined function in Python named showGrades (S) which
takes the dictionary S as an argument. The dictionary, S contains Name: [Eng,
Math, Science] as key:value pairs. The function displays the corresponding grade
obtained by the students according to the following grading rules:
Average of Eng, Math, Science Grade
>=90 A
<90 but >=60 B
<60 C

For example: Consider the following dictionary


S={"AMIT": [92,86,64], "NAGMA": [65,42,43], "DAVID": [92,90,88]}

The output should be :


AMIT - B
NAGMA - C
DAVID – A
Solution:
def showGrades(S):
for name, marks in S.items():
avg = sum(marks) / len(marks)
if avg >= 90:
grade = 'A'
elif avg >= 60:
grade = 'B'
else:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

grade = 'C'
print(f"{name} - {grade}")

# Example usage:
S = {"AMIT": [92, 86, 64], "NAGMA": [65, 42, 43], "DAVID": [92, 90, 88]}
showGrades(S)
Explanation:
 The function loops through each key-value pair in the dictionary.
 It calculates the average marks using the built-in sum() and len()
functions.
 It then assigns the grade based on the given conditions and prints the
result in the required format.

Ques. 27 Write a user defined function in Python named Puzzle (W, N) which
takes the argument W as an English word and N as an integer and returns the
string where every Nth alphabet of the word w is replaced with an underscore
(“_”)
For example: if w contains the word "TELEVISION" and N is 3, then the
function should return the string " TE_ EV_ SI_ N. Likewise for the word
"TELEVISION" if N is 4, then the function should return "TEL_VIS_ON".
(CBSE 2024)
Program:
def puzzle(W,N):
str=""
for i in range(1,len(W)+1):
if i%N==0:
str+="_"
else:
str+=W[i-1]
return str

your_word=str(input("Enter String: "))


nvalue=int(input("Enter a number: "))
print("Word: ", puzzle(your_word,nvalue))

3 MARKER QUESTIONS

Output Based Question

Ques. 28 Write the output on execution of the following Python code :


(CBSE 2024)
S="Racecar Car Radar"
L=S.split()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

for W in L:
x=W.upper()
if x==x[::-1]:
for I in x:
print(I,end="*")
else:
for I in W:
print(I,end="#")
print()

Step-by-Step Analysis:
1. Splitting the String:
S.split() divides the string by spaces, resulting in the list:
["Racecar", "Car", "Radar"]
2. Processing Each Word:
o Word 1: "Racecar"
 x = "Racecar".upper() → "RACECAR"
 Since "RACECAR" reversed is "RACECAR", the condition is
true.
 The inner loop prints each character of "RACECAR" followed
by "*".
 Output line:
R*A*C*E*C*A*R*
o Word 2: "Car"
 x = "Car".upper() → "CAR"
 Reversed "CAR" is "RAC", which is not equal to "CAR".
 The else branch prints each character of "Car" (as is) followed
by "#".
 Output line:
C#a#r#
o Word 3: "Radar"
 x = "Radar".upper() → "RADAR"
 Reversed "RADAR" is "RADAR", so the condition is true.
 The inner loop prints each character of "RADAR" followed by
"*".
 Output line:
R*A*D*A*R*
Final Output:
R*A*C*E*C*A*R*
C#a#r#
R*A*D*A*R*
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 29 Predict the output of the following code: (SQP 2025)

d = {"apple": 15, "banana": 7, "cherry":9}


str1 = ""
for key in d:
str1 = strl + str(d[key]) + "@" + "\n"
str2 = str1[:-1]
print(str2)

Step-by-Step Analysis:
 Dictionary Iteration:
The dictionary is iterated in the order of insertion: "apple", "banana", then
"cherry".
 Building the String:
o For "apple":
str1 becomes "15@\n".
o For "banana":
str1 becomes "15@\n7@\n".
o For "cherry":
str1 becomes "15@\n7@\n9@\n".
 Final Adjustment:
str2 = str1[:-1] removes the last newline.
Final Output:
15@
7@
9@

Ques. 30 Predict the output of the following code: (SQP 2025)

line=[4,9,12,6,20]
for I in line:
for j in range(1,I%5):
print(j,'#',end="")
print()

Step-by-Step Execution
1. For I = 4:
o Compute: 4 % 5 is 4 (since 4 is less than 5, remainder is 4).
o Range: range(1, 4) generates: 1, 2, 3.
o Output: The inner loop prints:
 For j = 1: prints 1 #
 For j = 2: prints 2 #
 For j = 3: prints 3 #
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

o Line Output:
1 #2 #3 #
2. For I = 9:
o Compute: 9 % 5 is 4 (9 divided by 5 leaves a remainder of 4).
o Range: range(1, 4) → 1, 2, 3.
o Output:
1 #2 #3 #
3. For I = 12:
o Compute: 12 % 5 is 2 (12 divided by 5 gives remainder 2).
o Range: range(1, 2) generates: 1.
o Output:
1#
4. For I = 6:
o Compute: 6 % 5 is 1.
o Range: range(1, 1) is empty (since the start value is not less than
the end value).
o Output: An empty line (no output).
5. For I = 20:
o Compute: 20 % 5 is 0 (20 is exactly divisible by 5).
o Range: range(1, 0) is empty.
o Output: Another empty line.
Final Output
The program will print five lines corresponding to each element in line:
less
1 #2 #3 #
1 #2 #3 #
1#

(The 4th and 5th lines are blank.)


Explanation Recap
 I = 4 and I = 9: Both yield a remainder of 4, so the inner loop runs with j
taking 1, 2, and 3.
 I = 12: Yields a remainder of 2, so only j = 1 is printed.
 I = 6: Yields a remainder of 1, causing an empty range.
 I = 20: Yields a remainder of 0, also causing an empty range.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

EXCEPTION HANDLING
1 Mark Questions
True False Questions
Ques. 1 State whether the statement is True or False: (CBSE 2024)
While handling exceptions in Python, name of the exceptions has to be
compulsorily added with except clause.
Answer: False – In Python, using an except clause without specifying an
exception name is allowed. It is called a generic exception handler (except:).
Ques. 2 State True or False: (SQP 2025)
The Python interpreter handles logical errors during code execution.
Answer: False – The Python interpreter does not handle logical errors (such as
incorrect logic in a program). Logical errors need to be identified and corrected
by the programmer.
Ques. 3 State whether the following statement is True or False: (SQP 2025)
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.

FILE HANDLING
TEXT FILE:
1 Marker Question
MCQs
Ques. 1 Which of the following mode keeps the file offset position at the end of
the file? (CBSE 2023)
(a) r+ (b) r
(c) w (d) a
Answer: (d) a – The a (append) mode keeps the file offset at the end of the file.
Ques. 2 The syntax of seek( ) is: (CBSE 2023)
file_object.seek(offset[,reference_point])
What is the default value of reference_point
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Answer: The default value of reference_point in seek(offset, reference_point) is 0,


meaning it refers to the beginning of the file.
Ques. 3 Consider the following Python Statement: (CBSE 2024)
F=open(“CONTENT.TXT”)
Which of the following is an invalid statement in Python?
(a) F.seek(1,0)
(b) F.seek(0,1)
(c) F.seek(0,-1)
(d) F.seek(0,2)
Answer: (c) F.seek(0,-1) – This is invalid because the reference point -1
(backward movement from the current position) is not allowed in seek().
Ques. 4 Write the missing statement to complete the following code: (SQP 025)

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) # Move the file pointer to the beginning of the file

High Weightage Questions(4/5 Marker)


Ques. 1 Write the definition of a Python function named LongLines( ) which
reads the contents of a text file named 'LINES.TXT' and displays those lines
from the file which have at least 10 words in it. For example, if the content of
'LINES.TXT' is as follows: (CBSE 2O23) (3 Marks)

Once upon a time, there was a woodcutter


He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.
Then the function should display output as:
He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.

Ans.
def LongLines():
try:
with open("LINES.TXT", "r") as file:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

for line in file:


words = line.split()
if len(words) >= 10:
print(line.strip()) # Printing without extra newline
except FileNotFoundError:
print("File 'LINES.TXT' not found.")

# Call the function


LongLines()

Ques. 2 Write a user defined function in Python named showInLines () which


reads contents of a text file named STORY.TXT and displays every sentence in a
separate line. (CBSE 2024)
Assume that a sentence ends with a full stop (.), a question mark (?), or an
exclamation mark (!).
For example, if the content of file STORY. TXT is as follows:
Our parents told us that we must eat vegetables to be healthy. And it turns out,
our parents were right! So, what else did our parents tell?

Then the function should display the file's content as follows :


Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell?
Ans.
def showInLines():
try:
with open("STORY.TXT", "r") as file:
content = file.read()

sentence = ""
for char in content:
sentence += char # Add character to sentence
if char in ".!?": # Check if it's a sentence-ending character
print(sentence.strip()) # Print sentence
sentence = "" # Reset for next sentence

except FileNotFoundError:
print("File not found!")

# Call the function


showInLines()

Ques. 3 Write a Python function that displays all the words containing @cmail
from a text file "Emails.txt". (CBSE SQP 2025)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ans.
def display_cmail():
try:
with open("Emails.txt","r") as file:
words=file.read() #whole file as a single string
word=words.split() #list of strings
for i in word:
if "@cmail" in i:
print(i)

except Exception as exp:


print("Error Occured: ",exp)

display_cmail()

Ques. 4 Write a Python function that finds and displays all the words longer
than 5 characters from a text file "Words.txt". (CBSE SQP 2025)

Ans.
def Display_long():
try:
with open("Wordss.txt","r") as file:
words=file.read() #complete file content in a single string
word=words.split()
for i in word:
if len(i)>5:
print(i)

except Exception as exp:


print("Error Occured: ",exp)

Display_long()

Ques. 5 Write a function count_Dwords() in Python to count the words ending


with a digit in a text file "Details.txt". (CBSE 2023)

Example:
If the file content is as follows:
On seat2 VIP1 will sit and On seat1 VVIP2 will be sitting

Output will be:


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Number of words ending with a digit are 4

Ans.
def count_Dwords():
count=0
with open("Details.txt","r") as file:
content=file.read()
words=content.split()
for word in words:
if word[-1] in "012345678":
count+=1
return count

print("The number of words ending with a digit are ", count_Dwords())

Ques. 6 Write a function, c_words() in Python that separately counts and


displays the number of uppercase and lowercase alphabets in a text file,
Words.txt. (CBSE 2024)

Ans.
def c_words():
up_count=0
low_count=0
with open("Words.txt","r") as file:
content=file.read()
for char in content:
if char.isupper()==True:
up_count+=1
elif char.islower()==True:
low_count+=1
else:
continue
print("No of uppercase characters: ",up_count)
print("No of lowercase characters: ",low_count)

c_words()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

BINARY FILE:
Ques. 7 Shreyas is a programmer, who has recently been given a task to write a
user defined function named write bin() to create a binary file called Cust file.dat
containing customer information customer number (cno), name (e name),
quantity (qty), price (price) and amount (amt) of each customer.

The function accepts customer number, name, quantity and price. Thereafter, it
displays the message 'Quantity less than 10..... Cannot SAVE, if quantity
entered is less than 10. Otherwise the function calculates amount as price.
quantity and then writes the record in the form of a list into the binary file.
(CBSE 2023)

import pickle

def write bin():


bin file=_______________#Statement 1

while True:
cno=int(input("enter customer number"))
cname=input("enter customer name")
qty=int(input("enter qty"))
price=int(input("enter price"))

if _____________#Statement 2
print "Quantity less than 10..Cannot SAVE

else:
amt=price*qty
c_detail=[c_no,c_name,qty, price,amt]
_________________#Statement 3
ans=input ("Do you wish to enter more records y/n")
if ans.lower()=='n':
_____________#Statement 4
________________#Statement 5
__________________#Statement 6

(i) Write the correct statement to open a file 'Cust_file.dat' for writing the
data of the customer.
(ii) Which statement should Shreyas fill in Statement 2 to check whether
quantity is less than 10.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(iii) Which statement should Shreyas fill in Statement 3 to write data to


the binary file and in Statement 4 to stop further processing if the user
does not wish to enter more records.

Ans.
Statement 1:
bin_file = open("Cust_file.dat", "wb")
Statement 2:
if qty < 10:
Statement 3:
pickle.dump(c_detail, bin_file)
Statement 4:
break
Statement 5:
bin_file.close()

Ques. 7 Consider a binary file, items.dat, containing records stored in the given
format :
{item_id: [item_name, amount]}

Write a function, Copy_new(), that copies all records whose amount is greater
than 1000 from items.dat to new_items.dat. (CBSE 2024)

import pickle
def Copy_new():
try:
with open("items.dat","rb") as infile:
records=pickle.load(infile)

dict={}
for key, value in records.items():
if value[1]>1000:
dict[key]=value

with open("new_records.dat","wb") as outfile:


pickle.dump(dict,outfile)
except Exception as exp:
print("Error Occured: ", exp)

Copy_new()

Ques. 8 A binary file, EMP. DAT has the following structure: (CBSE 2024)
[Emp_Id, Name, Salary]
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

where
Emp_Id: Employee id
Name: Employee Name
Salary: Employee Salary

Write a user defined function, disp_Detail(), that would read the contents of the
file EMP. DAT and display the details of those employees whose salary is below
25000.

def disp_Details():
with open("emp.dat","rb") as file:
while True:
try:
records=pickle.load(file)
if records["Salary"]<25000:
print(records)
print("Record Fetched Sucessfully!")
except EOFError:
break

disp_Details()

Ques. 9 Surya is a manager working in a recruitment agency. He needs to


manage the records of various candidates. For this, he wants the following
information of each candidate to be stored: (SQP 2025)

Candidate_ID - integer
Candidate_Name - string
Designation - string
Experience - float

You, as a programmer of the company, have been assigned to do this job for
Surya.

(I) Write a function to input the data of a candidate and append it in a binary
file.

(II) Write a function to update the data of candidates whose experience is more
than 10 years and change their designation to "Senior Manager".

(III) Write a function to read the data from the binary file and display the data of
all those candidates who are not "Senior Manager".
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

import pickle
def append_data():
candidate_ID=int(input("Enter Candidate ID: "))
candidate_Name=str(input("Enter Candidate Name: "))
designation=str(input("Enter Designation: "))
exp=float(input("Enter Experience: "))
with open("Candidate_data.dat","ab") as file:
new_data={"ID":candidate_ID,"Name":candidate_Name,"Designation":desig
nation,"Experience":exp}
pickle.dump(new_data,file)
print("Candidate Data added successfully!")

def update_data():
records=[]
with open("candidate_data.dat","rb") as file:
while True:
try:
records.append(pickle.load(file))
except EOFError:
break
for record in records:
if record["Experience"]>10:
record["Designation"]="Senior Manager"

with open("candidate.dat","wb") as file:


for record in records:
pickle.dump(record,file)

print("Data Updated Successfully!")

def read_candidate():
with open("candidate_data.dat","rb") as file:
while True:
try:
record=pickle.load(file)
print(record)
except EOFError:
break
print("Data fetched Sucessfully!")

read_candidate()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

CSV FILE:

Ques. 10 Write one difference between CSV and text files. Write a program in
Python that defines and calls the following user defined functions: (CBSE 2023)

(i) COURIER_ADD(): It takes the values from the user and adds the details to a
csv file 'courier.csv'. Each record consists of a list with field elements as cid,
s_name, Source, destination to store Courier ID, Sender name, Source and
destination address respectively.

(ii) COURIER_SEARCH(): Takes the destination as the input and displays all
the courier records going to that destination.

import csv
def courier_add():
#input details
cid=int(input("Enter Courier ID: "))
sname=str(input("Enter Sender Name: "))
source=str(input("Enter Source address: "))
dest=str(input("Enter Destination address: "))
try:
with open("courier.csv","a",newline="") as file:
writer=csv.writer(file)
writer.writerow([cid,sname,source,dest])
except Exception as exp:
print("Error Occured: ",exp)

def courier_search():
dest_input=str(input("Enter Destination: "))
try:
with open("courier.csv","r",newline="") as file:
reader=csv.reader(file)
for data in reader:
if data[-1]==dest_input:
print(data)
except Exception as exp:
print("Error Occurred: ",exp)

courier_search()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 11 Why it is important to close a file before exiting? (CBSE 2023)

Write a program in Python that defines and calls the following user defined
functions:

(i) Add_Book(): Takes the details of the books and adds them to a csv file
'Book.csv'. Each record consists of a list with field elements as book ID, B_name
and pub to store book ID, book name and publisher respectively.

(ii) Search_Book(): Takes publisher name as input and counts and displays
number of books published by them.

Ques. 12 Sangeeta is a Python programmer working in a computer hardware


company. She has to maintain the records of the peripheral devices. She created
a csv file named Peripheral.csv, to store the details. The structure of
Peripheral.csv is:

[P_id, P_name, Price]


where
P_id is Peripheral device ID (integer)
P_name is Peripheral device name (String)
Price is Peripheral device price (integer)
Sangeeta wants to write the following user defined functions:

(i) Add_Device(): to accept a record from the user and add it to a csv file,
Peripheral.csv.

(ii) Count_Device(): To count and display number of peripheral devices whose


price is less than 1000.

import csv
def Add_Device():
p_id=int(input("Enter Peripheral device id: "))
p_name=str(input("Enter Peripheral device name: "))
price=int(input("Enter price: "))
records=[]
try:
with open("Peripheral.csv","a",newline="") as file:
writer=csv.writer(file)
writer.writerow([p_id,p_name,price])
except Exception as exp:
print("Error Occured: ",exp)

def Count_Device():
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

count=0
try:
with open("Peripheral.csv","r",newline="") as file:
reader=csv.reader(file)
for data in reader:
if int(data[-1])<1000:
print(data)
count+=1
print("No of devices: ", count)
except Exception as exp:
print("Error Occured: ", exp)

Count_Device()

Ques. 13 A csv file "Happiness.csv" contains the data of a survey. Each record of
the file contains the following data: (SQP 2025)
Name of a country
Population of the country

Sample Size (Number of persons who participated in the survey in that country)
Happy (Number of persons who accepted that they were Happy)

For example, a sample record of the file may be:

['Signiland', 5673000, 5000, 3426]

Write the following Python functions to perform the specified operations on this
file:

(I) Read all the data from the file in the form of a list and display all those
records for which the population is more than 5000000.

(II) Count the number of records in the file.

import csv
def large_numbers():
records=[]
try:
with open("Happiness.csv",newline="") as filee:
csv_record=csv.reader(filee)
for record in csv_record:
try:
if int(record[1])>5000000:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

records.append(record)
except:
continue
for i in records:
print(i)
except Exception as exp:
print("File Error: ",exp)

large_numbers()

def count_record():
count=0
try:
with open("Happiness.csv",newline="") as filee:
csv_records=csv.reader(filee)
for record in csv_records:
count+=1
print("Total number of records: ",count)
except Exception as exp:
print("Error reading file: ",exp)

count_record()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

STACK
1 Marker Question
Assertion Reason
Ques. 1 (CBSE 2023)
Assertion (A): A stack is a LIFO structure.
Reason (R): Any new element pushed into the stack always gets positioned at the
index after the last existing element in the stack.

4 Marker Question
Ques. 2 A list contains following record of customer: (CBSE 2023)
[Customer_name, Room Type)
Write the following user defined functions to perform given operations on the
stack named 'Hotel':

(i) Push Cust() - To Push customers' names of those customers who are staying in
'Delux' Room Type.
ii) Pop_Cust() - To Pop the names of customers from the stack and display them.
Also, display "Underflow" when there are no customers in the stack.

For example:
If the lists with customer details are as follows:
["Siddarth", "Delux"]
["Rahul", "Standard"]
["Jerry", "Delux"]

The stack should contain


Jerry
Siddharth

The output should be:


Jerry
Siddharth
Underflow

PROGRAM:
Hotel = [] # Stack to store customers in Delux room
customer_list = [["Siddharth", "Delux"], ["Rahul", "Standard"], ["Jerry", "Delux"]]

def Push_Cust(Hotel, customer_list):


for detail in customer_list:
if detail[1] == "Delux":
Hotel.append(detail[0])
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

def Pop_Cust(Hotel):
if len(Hotel) == 0:
print("Underflow")
else:
print(Hotel.pop())

# Pushing Delux room customers into the stack


Push_Cust(Hotel, customer_list)

# Popping and displaying customer names


Pop_Cust(Hotel) # Jerry
Pop_Cust(Hotel) # Siddharth
Pop_Cust(Hotel) # Underflow

Ques. 3 Write a function in Python, Push (Vehicle) where, Vehicle is a dictionary


containing details of vehicles - (Car_Name: Maker). The function should push the
name of car manufactured by 'TATA' (including all the possible cases like Tata,
TaTa, etc.) to the stack. (CBSE 2023)

For example:
If the dictionary contains the following data:
Vehicle={"Santro":"Hyundai", "Nexon":"TATA", "Safari":"Tata"}

The stack should contain


Safari
Nexon

PROGRAM:
def Push(Vehicle, stack):
for car, maker in Vehicle.items():
if maker.lower() == "tata": # Convert maker to lowercase to check all cases
stack.append(car) # Push only the car name

# Example Dictionary
Vehicle = {"Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}

# Stack to store TATA cars


stack = []

# Calling the function


Push(Vehicle, stack)

# Displaying the stack


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

print("Stack:", stack)

Ques. 4 Consider a list named Nums which contains random integers.


(CBSE 2024)

Write the following user defined functions in Python and perform the specified
operations on a stack named BigNums.

(i) PushBig(): It checks every number from the list Nums and pushes all such
numbers which have 5 or more digits into the stack, BigNums.

(ii) PopBig(): It pops the numbers from the stack, BigNums and displays them.
The function should also display "Stack Empty" when there are no more
numbers left in the stack.

For example: If the list Nums contains the following data: Nums =
[213,10025,167,254923,14,1297653, 31498, 386,92765] Then on execution of
PushBig(), the stack BigNums should store:

[10025, 254923, 1297653, 31498, 92765]

And on execution of PopBig (), the following output should be displayed:

92765
31498
1297653
254923
10025
Stack Empty

PROGRAM:
BigNums = [] # Stack to store numbers with 5 or more digits

def PushBig(Nums):
"""Push numbers with 5 or more digits into the stack BigNums."""
for num in Nums:
if num >= 10000: # Check if the number has 5 or more digits
BigNums.append(num)

def PopBig():
"""Pop and display numbers from the stack. Show 'Stack Empty' if the stack is
empty."""
if not BigNums: # Check if the stack is empty
print("Stack Empty")
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

else:
while BigNums: # Pop until the stack is empty
print(BigNums.pop()) # Display popped value
print("Stack Empty") # Display once when all numbers are popped

# Example list
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]

# Pushing numbers with 5 or more digits


PushBig(Nums)

# Displaying the stack before popping


print("Stack before popping:", BigNums)

# Popping and displaying numbers


PopBig()

Ques. 5 You have a stack named BooksStack that contains records of books. Each
book record is represented as a list containing book_title, author_name, and
publication_year. Write the following user-defined functions in Python to
perform the specified operations on the stack BooksStack: (SQP 2025)

(1) push_book(BooksStack, new_book): This function takes the stack BooksStack


and a new book record new_book as arguments and pushes the new book record
onto the stack.

(II) pop_book(BooksStack): This function pops the topmost book record from the
stack and returns it. If the stack is already empty, the function should display
"Underflow".

(III) peep(BookStack): This function displays the topmost element of the stack
without deleting it. If the stack is empty, the function should display 'None'.

PROGRAM:
BooksStack=[]

def push_book(BooksStack,new_book):
BooksStack.append(new_book)

def pop_book(BooksStack):
if len(BooksStack)==0:
return "Underflow"
else:
BooksStack.pop()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

def peek(BooksStack):
if len(BooksStack)==0:
return "None"
else:
element=BooksStack[-1]
print(element)

def display(BooksStack):
print(BooksStack)

push_book(BooksStack,["Zero to One", "Peter Thiel",1983])


push_book(BooksStack,["Zero", "Thiel",1993])
display(BooksStack)
print(peek(BooksStack))

Ques. 6 Write the definition of a user-defined function 'push_even(N)' which


accepts a list of integers in a parameter 'N' and pushes all those integers which
are even from the list 'N' into a Stack named 'EvenNumbers'. Write function
pop_even() to pop the topmost number from the stack and returns it. If the stack
is already empty, the function should display "Empty". (SQP 2025)

Write function Disp_even() to display all element of the stack without deleting
them. If the stack is empty, the function should display 'None'.

For example:
If the integers input into the list 'VALUES' are: [10, 5, 8, 3, 12]
Then the stack 'EvenNumbers' should store: [10, 8, 12]

PROGRAM:
EvenNumbers = [] # Stack to store even numbers

def push_even(EvenNumbers, N):


for i in N:
if i % 2 == 0:
EvenNumbers.append(i)

def pop_even(EvenNumbers):
if not EvenNumbers:
print("Empty")
else:
print(EvenNumbers.pop())

def Disp_even(EvenNumbers):
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

if len(EvenNumbers)==0:
print("None")
else:
print(*EvenNumbers) # Print elements without removing them

# Example list
N = [82, 49, 48, 29, 59, 25, 92]

# Pushing even numbers


push_even(EvenNumbers, N)

# Display stack (should not pop elements)


Disp_even(EvenNumbers) # Output: 82 48 92

# Pop elements
pop_even(EvenNumbers) # Output: 92
pop_even(EvenNumbers) # Output: 48

# Display again after popping


Disp_even(EvenNumbers) # Output: 82

# Emptying the stack


pop_even(EvenNumbers) # Output: 82
pop_even(EvenNumbers) # Output: Empty

# Final Display when stack is empty


Disp_even(EvenNumbers) # Output: None
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

COMPUTER NETWORKING
1 Marker Questions
MCQs
Ques. 1 Fill in the blank: (CBSE 2023)
_______________is used for point-to-point communication or unicast
communication such as radar and satellite.

(a) INFRARED WAVES


(c) MICROWAVES
(b) BLUETOOTH
(d) RADIOWAVES
Answer: (c) MICROWAVES

Ques. 2 (CBSE 2023)


(a) Differentiate between wired and wireless transmission.
(b) Differentiate between URL and domain name with the help of an appropriate
example.
(a) Difference between wired and wireless transmission:
Wired Transmission Wireless Transmission
Uses physical cables (e.g., Ethernet, Uses electromagnetic waves (e.g., Wi-Fi,
fiber optics). Bluetooth).
Prone to interference and security
More reliable and secure.
issues.
Higher speed and lower latency. Lower speed and higher latency.
Installation cost is high. Easy to set up and cost-effective.
(b) Difference between URL and Domain Name with an example:
URL (Uniform Resource Locator) Domain Name
The complete web address of a page. The main part of a website’s address.
Includes protocol, domain name, and path. Only represents the website’s name.
Example: https://www.google.com/search Example: google.com

Ques. 3
(a) Write the full forms of the following: (CBSE 2023)
(i) HTML
(ii) TCP
(b) What is the need of Protocols ?
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(a) Full Forms:


(i) HTML – HyperText Markup Language
(ii) TCP – Transmission Control Protocol
(b) Need for Protocols:
Protocols define rules for communication between devices over a network. They
ensure:
 Successful and reliable data transmission
 Standardized communication between different devices
 Error detection and correction (e.g., TCP/IP, HTTP, FTP)

Ques. 4 Which protocol out of the following is used to send and receive emails
over a computer network? (CBSE 2024)
(a) PPP
(b) HTTP
(c) FTP
(d) SMTP
Correct Answer: (d) SMTP (Simple Mail Transfer Protocol) is used to send and
receive emails over a computer network.

Ques. 5 Which of the following options is the correct unit of measurement for
network bandwidth ? (CBSE 2024)
(a) KB
(b) Bit
(c) Hz
(d) Km
Correct Answer: (b) Bit is the correct unit of measurement for network
bandwidth.

Ques. 6 Fill in the blank: (CBSE 2024)


________________is a set of rules that needs to be followed by the communicating
parties in order to have a successful and reliable data communication over a
network.
Protocol is a set of rules that needs to be followed by the communicating parties
in order to have a successful and reliable data communication over a network.

Ques. 7 (CBSE 2024)


(i) Expand the following terms:
XML, PPP
(ii) Give one difference between circuit switching and packet switching.
(i) Expand the following terms:
 XML – eXtensible Markup Language
 PPP – Point-to-Point Protocol
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(ii) One difference between circuit switching and packet switching:


Circuit Switching Packet Switching
A dedicated communication path is Data is divided into packets sent
established. independently.
Suitable for voice communication. Suitable for internet data transfer.
Example: Telephone networks. Example: Internet communication.

Ques. 8 (CBSE 2024)


(i) Define the term web hosting.
(ii) Name any two web browsers.
(i) Definition of Web Hosting:
Web hosting is a service that allows individuals and organizations to store and
publish their websites on the internet. Hosting providers offer servers where
website files are stored.
(ii) Two Web Browsers:
1. Google Chrome
2. Mozilla Firefox

Ques. 9 Which protocol is used to transfer files over internet?


(a) HTTP
(b) FTP
(c) PPP
(d) HTTPS
Answer: (b) FTP

Ques. 10 Which network device is used to connect two networks that use
different protocols?
(a) Modem
(b) Gateway
(c) Switch
(d) Repeater
Answer: Gateway

Ques. 11 Which Switching technique breaks data into packets for transmission,
allowing multiple packets to share the same network resources?
Answer: Packet Switching

Ques. 12
A) List one advantage and one disadvantage of star topology.
B) Expand the term SMTP. What is the use of SMTP?

A) Advantage and Disadvantage of Star Topology:


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

 Advantage: If one computer or device fails, it does not affect the rest of the
network.
 Disadvantage: It requires more cable length and a central hub, making it
expensive.
B) SMTP (Simple Mail Transfer Protocol):
 Expansion: Simple Mail Transfer Protocol
 Use: SMTP is used to send and relay outgoing emails between mail
servers over the internet.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Network Expert Questions


Ques. 13 (CBSE 2023)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Answer:
(i) Server at branch D because it has maximum number of computers.
(ii)

(iii) Switch should be placed in each of these branches to efficiently connect all
the computers within these branches.
(iv) WAN as the limit is more than 100 kms.
(v) To transfer files from Delhi to Kanpur branch, FTP is the best protocol
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 14 (CBSE 2024)


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Answer:
(i)

Trishula
Vajra

Sudarshana

(ii) Server hos ng: Host the server at Vajra due to the highest number of computers (120).
(iii) Transmission medium: Use op cal fiber for the long-distance connec on to Bengaluru
office.
(iv) Internal network device: Use a switch to connect devices within each loca on.
(v) Device for data transmission: Use a repeater to mi gate signal degrada on.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 15 (SQP 2025)


#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Answer:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

DBMS
1 Marker Questions
Ques. 1 _____________ is a number of tuples in a relation. (CBSE 2023)
(a) Attribute
(b) Degree
(c) Domain
(d) Cardinality
Solution:
The term that denotes the number of tuples (rows) in a relation is Cardinality.
Answer: (d) Cardinality
Ques. 2 If a table which has one primary key and two alternate keys. How many
Candidate keys will this table have? (SQP 2025)
(a) 1
(b) 2
(c) 3
(d) 4
Solution:
A candidate key is any attribute (or set of attributes) that can uniquely identify a
tuple. If one candidate is chosen as the primary key, the remaining candidate
keys are called alternate keys. Here, with one primary key and two alternate
keys, there are a total of 3 candidate keys.
Answer: (c) 3

2 Marker Questions
Ques. 3 Explain the concept of “Alternate Key” in a Relational Database
Management System with an appropriate example. (CBSE 2023)
Solution:
An Alternate Key is a candidate key that was not selected as the primary key. It
is still a unique identifier for tuples but is not used as the main means of
identification.
Example: Consider a table STUDENT with the following attributes:
 Student_ID
 Email
 Phone_Number
If Student_ID is chosen as the primary key, then both Email and Phone_Number
(assuming each is unique) are alternate keys. They are capable of uniquely
identifying a student but are not the primary key.
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Explanation: Alternate keys provide flexibility in uniquely accessing records if


needed, and can be used for enforcing uniqueness in other columns.

4 Marker Questions
Ques. 4 The school has asked their estate manager Mr. Rahul to maintain the
data of all the labs in a table LAB. Rahul has created a table and entered data of
5 labs. (CBSE 2023)

LABNO LAB_NAME INCHARGE CAPACITY FLOOR


L001 CHEMISTRY Daisy 20 I
L002 BIOLOGY Venky 20 II
L003 MATH Preeti 15 I
L004 LANGUAGE Daisy 36 III
L005 COMPUTER Mary Kom 37 II
Based on the data given above answer the following questions:
(i) Identify the columns which can be considered as Candidate keys.
Solution:
 LABNO: This is unique for every lab.
 LAB_NAME: All lab names are distinct in the given data.
Thus, LABNO and LAB_NAME can both serve as candidate keys.

(ii) Write the degree and cardinality of the table.


Solution:
 Degree: The number of attributes (columns) in the table. Here, there are 5
columns (LABNO, LAB_NAME, INCHARGE, CAPACITY, FLOOR).
 Cardinality: The number of tuples (rows) in the table. Here, there are 5
labs.
Answer:
 Degree = 5
 Cardinality = 5

(iii) Write the statements to:


(a) Insert a new row with appropriate data.
(b) Increase the capacity of all the labs by 10 students which are on 'I' Floor.
(a) Insert a new row with appropriate data.
Sample SQL Statement:
INSERT INTO LAB (LABNO, LAB_NAME, INCHARGE, CAPACITY, FLOOR)
VALUES ('L006', 'PHYSICS', 'Rahul', 25, 'I');
(b) Increase the capacity of all the labs by 10 students which are on 'I' Floor.
Sample SQL Statement:
UPDATE LAB
SET CAPACITY = CAPACITY + 10
WHERE FLOOR = 'I';
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

STRUCTURED QUERY LANGUAGE (SQL)


1 MARKER QUESTIONS
Fill in the blank/MCQs:
Ques. 1 ______________ clause is used with SELECT statement to display data in
a sorted form with respect to a specified column. (CBSE 2023)
(a) WHERE
(b) ORDER BY
(c) HAVING
(d) DISTINCT
Solution:
The clause used to sort the output is ORDER BY.
Answer: (b) ORDER BY
Ques. 2 The SELECT statement when combined with _____________ clause,
returns records without repetition. (CBSE 2024)
(a) DISTINCT
(b) DESCRIBE
(c) UNIQUE
(d) NULL
Solution:
The keyword that returns unique records is DISTINCT.
Answer: (a) DISTINCT
Ques. 3 In SQL, the aggregate function which will display the cardinality of the
tables is _______________. (CBSE 2024)
(a) sum()
(b) count(*)
(c) avg()
(d) sum(*)
Solution:
To display the number of rows (cardinality), we use count(*).
Answer: (b) count(*)
Ques. 4 Which of the following is not a DDL command in SQL? (CBSE 2024)
(a) DROP
(b) CREATE
(c) UPDATE
(d) ALTER
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Solution:
UPDATE is a Data Manipulation Language (DML) command, not a Data
Definition Language (DDL) command.
Answer: (c) UPDATE
Ques. 5 What will be the output of the query? (SQP 2025)
SELECT * FROM PRODUCTS WHERE PRODUCT_NAME LIKE “App%”;
(a) Details of all products whose names start with “App”
(b) Details of all products whose names end with “App”
(c) Names of all products whose names start with “App”
(d) Names of all products whose names start with “App”
Solution:
The query returns all columns (details) for products whose names begin with
“App”.
Answer: (a) Details of all products whose names start with “App”
Ques. 6 Which SQL Command can change the degree of an existing relation?
(SQP 2025)
Solution:
Changing the degree means adding or dropping columns. This is done using the
ALTER TABLE command.
Answer: ALTER TABLE
Ques. 7 In which datatype the value stored is padded with spaces to fit the
specified length. (SQP 2025)
(A) DATE
(B) VARCHAR
(C) FLOAT
(D) CHAR
Solution:
The CHAR datatype is fixed-length and pads values with spaces if needed.
Answer: (D) CHAR

Ques. 8 Which aggregate function can be used to find the cardinality of a table?
(SQP 2025)
(A) sum()
(B) count()
(C)avg()
(D)max()
Solution:
The count() function returns the number of rows in a table.
Answer: (B) count()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 9 (SQP 2025)


Assertion (A): A SELECT command in SQL can have both WHERE and HAVING
clauses.
Reasoning (R): WHERE and HAVING clauses are used to check conditions,
therefore, these can be used interchangeably.
Solution:
 Assertion (A) is true since a SELECT query may include both clauses.
 Reason (R) is false because while both clauses check conditions, WHERE
filters rows before grouping and HAVING filters groups after aggregation.
They are not interchangeable.
Answer: Assertion is true and Reason is false.

Ques. 10 (CBSE 2023)


(a) Consider the following tables - LOAN and BORROWER :

Table: LOAN

LOAN_NO B_NAME AMOUNT


L-170 DELHI 3000
L-230 KANPUR 4000

Table: BORROWER

CUST_NAME LOAN_NO
JOHN L-171
KRISH L-230
RAVYA L-170

How many rows and columns will be there in the natural join of these two
tables?
Solution:
The natural join is performed on the common attribute LOAN_NO. Only rows
with matching LOAN_NO in both tables will appear.
 LOAN_NO L-170: Matches with RAVYA
 LOAN_NO L-230: Matches with KRISH
Thus, the join will yield 2 rows.
The resulting relation will include all attributes from both tables but will not
duplicate the common column. So the columns will be: LOAN_NO, B_NAME,
AMOUNT, CUST_NAME.
Answer: 2 rows and 4 columns.

(b) Write the output of the queries (i) to (iv) based on the table. WORKER given
below:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

TABLE: WORKER

W_ID F_NAME L_NAME CITY STATE


102 SAHIL KHAN KANPUR UTTAR PRADESH
104 SAMEER PARIKH ROOP NAGAR PUNJAB
105 MARY JONES DELHI DELHI
106 MAHIR SHARMA SONIPAT HARYANA
107 ATHARVA BHARDWAJ DELHI DELHI
108 VEDA SHARMA KANPUR UTTAR PRADESH

(i) SELECT F_NAME, CITY FROM WORKER ORDER BY STATE DESC;


F_NAME CITY
SAHIL KANPUR
VEDA KANPUR
SAMEER ROOP NAGAR
MAHIR SONIPAT
MARY DELHI
ATHARVA DELHI
(ii) SELECT DISTINCT (CITY) FROM WORKER;
CITY
----------
KANPUR
ROOP NAGAR
DELHI
SONIPAT
(iii) SELECT F_NAME, STATE FROM WORKER WHERE L_NAME LIKE
'_HA%';
F_NAME STATE
SAHIL UTTAR PRADESH
MAHIR HARYANA
ATHARVA DELHI
VEDA UTTAR PRADESH
(iv) SELECT CITY, COUNT(*) FROM WORKER GROUP BY CITY;
CITY COUNT(*)
KANPUR 2
ROOP NAGAR 1
DELHI 2
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 11 (CBSE 2023)


(a) Write the outputs of the SQL queries (1) to (iv) based on the relations
COMPUTER and SALES given below:

Table: COMPUTER

PROD_ID PROD_NAME PRICE COMPANY TYPE


P001 MOUSE 200 LOGITECH INPUT
P002 LASER PRINTER 4000 CANON OUTPUT
P003 KEYBOARD 500 LOGITECH INPUT
P004 JOYSTICK 1000 IBALL INPUT
P005 SPEAKER 1200 CREATIVE OUTPUT
P006 DESKJET PRINTER 4300 CANON OUTPUT

Table: SALES

PROD_ID QTY_SOLD QUARTER


P001 4 1
P002 2 2
P003 3 2
P004 2 1

(i) SELECT MIN (PRICE), MAX(PRICE) FROM COMPUTER;


MIN(PRICE) MAX(PRICE)
200 4300

(ii) SELECT COMPANY, COUNT(*) FROM COMPUTER GROUP BY


COMPANY HAVING COUNT (COMPANY) > 1:
COMPANY COUNT(*)
LOGITECH 2
CANON 2
(iii) SELECT PROD_NAME, QTY_SOLD FROM COMPUTER C, SALES S
WHERE C. PROD ID=S.PROD ID AND TYPE INPUT:
PROD_NAME QTY_SOLD
MOUSE 4
KEYBOARD 3
JOYSTICK 2
(iv) SELECT PROD NAME, COMPANY, QUARTER FROM COMPUTER C,
SALES S WHERE C.PROD_ID=S.PROD_ID;
PROD_NAME COMPANY QUARTER
MOUSE LOGITECH 1
LASER PRINTER CANON 2
KEYBOARD LOGITECH 2
JOYSTICK IBALL 1
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(b) Write the command to view all databases.


SHOW DATABASES;

Ques. 12 (CBSE 2024)


(A) Ms. Veda created a table named Sports in a MySQL database. containing
columns Game_id, P_Age and G_name.

After creating the table, she realized that the attribute, Category has to be
added. Help her to write a command to add the Category column. Thereafter,
write the command to insert the following record in the table:

Game id: G42


P_Age: Above 18
G_name: Chess
Category: Senior
Solution:

1. Add the Column:


ALTER TABLE Sports
ADD COLUMN Category VARCHAR(50);
2. Insert the Record:
INSERT INTO Sports (Game_id, P_Age, G_name, Category) VALUES (G42,19
CHESS, SENIOR);

(B) Write the SQL commands to perform the following tasks:


(i) View the list of tables in the database, Exam.
(ii) View the structure of the table, Term1.

(i) View the list of tables in the database, Exam.


SHOW TABLES FROM Exam;
(ii) View the structure of the table, Term1.
DESCRIBE Term1;

Ques. 13 Consider the table ORDERS given below and write the output of the
SQL queries that follow:

ORDNO ITEM QTY RATE ORDATE


1001 RICE 23 120 2023-09-10
1002 PULSES 13 120 2023-10-18
1003 RICE 25 110 2023-11-17
1004 WHEAT 28 65 2023-12-25
1005 PULSES 16 110 2024-01-15
1006 WHEAT 27 55 2024-04-15
1007 WHEAT 25 60 2024-04-30
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(i) SELECT ITEM, SUM(QTY) FROM ORDERS GROUP BY ITEM:


ITEM SUM(QTY)
RICE 48
PULSES 29
WHEAT 80

(ii) SELECT ITEM, QTY FROM ORDERS WHERE ORDATE BETWEEN


“2023-11-01” AND “2023-12-31”
ITEM QTY
RICE 25
WHEAT 28

(iii) SELECT ORDNO, ORDATE FROM ORDERS WHERE ITEM = “WHEAT”


AND RATE>=60.
ORDNO ORDATE
1004 2023-12-25
1007 2024-04-30

Ques. 14 Consider the table Projects given below:

Table : Projects
Pid Pname Language Startdate Enddate
P001 School Management Python 2023-01-12 2023-04-03
System
P002 Hotel Management System C++ 2022-12-01 2023-02-02
P003 Blood Bank Python 2023-02-11 2023-03-02
P004 Payroll Management Python 2023-03-12 2023-06-02
System

Based on the given table, write SQL queries for the following:
(i) Add the constraint, primary key to column P_id in the existing table Projects.
ALTER TABLE Projects
ADD CONSTRAINT pk_Projects PRIMARY KEY (Pid);
(ii) To change the language to Python of the project whose id is P002.
UPDATE Projects
SET Language = 'Python'
WHERE Pid = 'P002';
(iii) To delete the table Projects from MySQL database along with its data.
DROP TABLE Projects;
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 15 Consider the tables Admin and Transport given below:

Table: Admin

Sid S_name Address S_type


S001 Sandhya Rohini Day Boarder
S002 Vedanshi Rohtak Day Scholar
S003 Vibhu Raj Nagar NULL
S004 Atharva Rampur Day Boarder

Table: Transport

Sid Bus_no Stop_name


S002 TSS10 Sarai Kale Khan
S004 TSS12 Sainik Vihar
S005 TSS10 Kamla Nagar

Write SQL queries for the following:

(i) Display the student name and their stop name from the tables Admin and
Transport.
SELECT A.S_name, T.Stop_name
FROM Admin A, Transport T
WHERE A.Sid = T.Sid;
(ii) Display the number of students whose s_type is not known.
SELECT COUNT(*) AS Unknown_Type_Count
FROM Admin
WHERE S_type IS NULL;
(iii) Display all details of the students whose name starts with 'V'.
SELECT *
FROM Admin
WHERE S_name LIKE 'V%';
(iv) Display student id and address in alphabetical order of student name, from
the table Admin.
SELECT Sid, Address
FROM Admin
ORDER BY S_name ASC;

Ques. 16
(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.
ALTER TABLE MOBILE
DROP PRIMARY KEY;
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(B) Write an SQL command to make the column M_ID the Primary Key of an
already existing table, named MOBILE.
ALTER TABLE MOBILE
ADD PRIMARY KEY (M_ID);

Ques. 17 Consider the table ORDERS as given below

O_Id C_Name Product Quantity Price


1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
Note: The table contains many more records than shown here.

A) Write the following queries:

(I) To display the total Quantity for each Product, excluding Products with total
Quantity less than 5.
SELECT Product, SUM(Quantity) AS Total_Quantity
FROM ORDERS
GROUP BY Product
HAVING SUM(Quantity) >= 5;

(II) To display the orders table sorted by total price in descending order.
SELECT *, (Quantity * Price) AS Total_Price
FROM ORDERS
ORDER BY Total_Price DESC;

(III) To display the distinct customer names from the Orders table.
SELECT DISTINCT C_Name
FROM ORDERS;

(IV) Display the sum of Price of all the orders for which the quantity is null.
SELECT SUM(Price) AS SumPrice
FROM ORDERS
WHERE Quantity IS NULL;

B) Write the output

(I) Select c_name, sum (quantity) as total_quantity from orders group by c_name;
c_name sum(quantity)
Jitendra 1
Mustafa 2
Dhwani 1
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

(II) Select * from orders where product like '%phone%';


O_Id C_Name Product Quantity Price
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500

(III) Select o_id, c_name, product, quantity, price from orders where price
between 1500 and 12000;
O_Id C_Name Product Quantity Price
1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500

(IV) Select max(price) from orders;


max(price)
----------------
12000

Ques. 18 Saman has been entrusted with the management of Law University
Database. He needs to access some information from FACULTY and COURSES
tables for a survey analysis. Help him extract the following information by
writing the desired SQL queries as mentioned below.

Table: FACULTY

F_ID FName LName Hire_Date Salary


102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-05-2001 14000
105 Rashmi Malhotra 11-09-2004 11000
106 Sulekha Srivastava 5-6-2006 10000

Table: COURSES
C_ID F_ID CName Fees
C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000

(I) To display complete details (from both the tables) of those Faculties whose
salary is less than 12000.
SELECT F.*, C.*
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

FROM FACULTY F, COURSES C


WHERE F.F_ID = C.F_ID
AND F.Salary < 12000;

(II) To display the details of courses whose fees is in the range of 20000 to 50000
(both values included).
SELECT *
FROM COURSES
WHERE Fees BETWEEN 20000 AND 50000;

(III) To increase the fees of all courses by 500 which have "Computer" in their
Course names.
UPDATE COURSES
SET Fees = Fees + 500
WHERE CName LIKE '%Computer%';

(IV)
(A) To display names (FName and LName) of faculty taking System Design.
SELECT F.FName, F.LName
FROM FACULTY F, COURSES C
WHERE F.F_ID = C.F_ID AND C.CName = 'System Design';

(B) To display the Cartesian Product of these two tables.


SELECT *
FROM FACULTY, COURSES;
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

PYTHON INTERFACING WITH MySQL


Ques. 1 The code given below deletes the record from the table employee which
contains the following record structure: (CBSE 2023)

E code - String
E_name String
Sal - Integer
City - String

Note the following to establish connectivity between Python and MySQL :

Username is root
Password is root
The table exists in a MySQL database named emp.
The details (E_code, E_name, Sal, City) are the attributes of the table.

Write the following statements to complete the code:

Statement 1- to import the desired library.


Statement 2 to execute the command that deletes the record with E_code as
'E101',
Statement 3 to delete the record permanently from the database.

import ______________ as mysql # Statement 1


def delete():
mydb=mysql.connect(host="localhost", user="root", passwd="root",
database="emp")

mycursor-mydb.cursor()

_____________________# Statement 2

______________________#Statement 3

print ("Record deleted")

Statement 1 = mysql.connector
Statement 2 = mycursor.execute("DELETE FROM employee WHERE
E_code='E101'")
Statement 3 = mydb.commit()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 2 The code given below reads the following records from the table
employee and displays only those records who have employees coming from city
'Delhi': (CBSE 2023)
E_code -String
E_name - String
Sal - Integer
City - String

Note the following to establish connectivity between Python and MySQL:

Username is zoot
Password is root
The table exists in a MySQL database named emp.
The details (E_code, E_name, Sal, City) are the attributes of the table.

Write the following statements to complete the code:

Statement 1 - to import the desired library.

Statement 2 - to execute the query that fetches records of the employees coming
from city “Delhi”.

Statement 3 - to read the complete data of the query (rows whose city is Delhi)
into the object named details, from the table employee in the database.

import ____________as mysql #Statement 1

def display():
mydb=mysql.connect(host "localhost", user="rt", passwd "root", database
"emp"]

mycursor=mydb.cursor()
_______________________#Statement 2

details=_____________________ #Statement 3

for i in details:
print (i)
Statement 1 = mysql.connector
Statement 2 = mycursor.execute("SELECT * FROM employee WHERE
City='Delhi'")
Statement 3 = details = mycursor.fetchall()
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

Ques. 3 (CBSE 2024)


(A) Sunil wants to write a program in Python to update the quantity to 20 of the
records whose item code is 111 in the table named shop in MySQL database
named Keeper.

The table shop in MySQL contains the following attributes:


Item_code: Item code (Integer)
Item_name: Name of item (String)
Qty: Quantity of item (Integer)
Price: Price of item (Integer)

Consider the following to establish connectivity between Python and MySQL:

Username: admin
Password: Shopping
Host: localhost

import mysql.connector as mysql

def update_qty():
mydb = mysql.connect(host="localhost", user="admin", passwd="Shopping",
database="Keeper")
mycursor = mydb.cursor()
mycursor.execute("UPDATE shop SET Qty = 20 WHERE Item_code = 111")
mydb.commit()
print("Quantity updated to 20 for Item_code 111")

(B) Sumit wants to write a code in Python to display all the details of the
passengers from the table flight in MySQL database, Travel. The table contains
the following attributes:

F_code: Flight code (String)


F_name: Name of flight (String)
Source: Departure city of flight (String)
Destination: Destination city of flight (String)

Consider the following to establish connectivity between Python and MySQL:


Username: root
Password: airplane
Host: localhost
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

import mysql.connector as mysql


def display_passengers():
mydb = mysql.connect(host="localhost", user="root", passwd="airplane",
database="Travel")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM flight")
details = mycursor.fetchall()
for row in details:
print(row)

Ques. 4 A table, named STATIONERY, in ITEMDB database, has the following


structure: (SQP 2025)

Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)

Write the following Python function to perform the specified operation:


AddAndDisplay(): To input details of an item and store it in the table
STATIONERY. The function should then retrieve and display all records from
the STATIONERY table where the Price is greater than 120.

Assume the following for Python-Database connectivity:


Host:localhost, User: root, Password: Pencil

Solution:
import mysql.connector as mysql

def AddAndDisplay():
mydb = mysql.connect(host="localhost", user="root", passwd="Pencil",
database="ITEMDB")
mycursor = mydb.cursor()

itemNo = int(input("Enter item number: "))


itemName = input("Enter item name: ")
price = float(input("Enter price: "))
qty = int(input("Enter quantity: "))

sql_insert = "INSERT INTO STATIONERY (itemNo, itemName, price, qty)


VALUES (%s, %s, %s, %s)"
values = (itemNo, itemName, price, qty)
mycursor.execute(sql_insert, values)
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE

mydb.commit()
mycursor.execute("SELECT * FROM STATIONERY WHERE price > 120")

records = mycursor.fetchall()

print("Records with Price greater than 120:")


for row in records:
print(row)

You might also like