Class 12 CS PYQs Compilation of Full Syllabus PDF by Nitin Paliwal
Class 12 CS PYQs Compilation of Full Syllabus PDF by Nitin Paliwal
CLASS 12
COMPUTER SCIENCE
1 MARKER QUESTIONS
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. 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
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
(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").
(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.
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
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
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.
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. 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.
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 = ’#’)
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'].
a=20
def convert(a):
b=20
a=a+b
convert(10)
print(a)
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".
country='International'
print (country.split("n"))
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.
2 MARKER QUESTIONS
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)
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
Ques. 21 Predict the output of the code given below : (CBSE 2023)
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
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.
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#
Miscellaneous Questions
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
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
3 MARKER QUESTIONS
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
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@
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#
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: file.seek(0) # Move the file pointer to the beginning of the file
Ans.
def LongLines():
try:
with open("LINES.TXT", "r") as file:
#MAHARATHI MATERIAL BY NITIN PALIWAL | CLASS 12 COMPUTER SCIENCE
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!")
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)
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)
Display_long()
Example:
If the file content is as follows:
On seat2 VIP1 will sit and On seat1 VVIP2 will be sitting
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
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
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
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
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()
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"
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
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.
(i) Add_Device(): to accept a record from the user and add it to a csv file,
Peripheral.csv.
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)
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.
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"]
PROGRAM:
Hotel = [] # Stack to store customers in Delux room
customer_list = [["Siddharth", "Delux"], ["Rahul", "Standard"], ["Jerry", "Delux"]]
def Pop_Cust(Hotel):
if len(Hotel) == 0:
print("Underflow")
else:
print(Hotel.pop())
For example:
If the dictionary contains the following data:
Vehicle={"Santro":"Hyundai", "Nexon":"TATA", "Safari":"Tata"}
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"}
print("Stack:", stack)
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:
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]
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)
(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)
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 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]
# Pop elements
pop_even(EvenNumbers) # Output: 92
pop_even(EvenNumbers) # Output: 48
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.
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
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. 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?
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
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
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
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
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)
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
Table: LOAN
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
Table: COMPUTER
Table: SALES
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:
Ques. 13 Consider the table ORDERS given below and write the output of the
SQL queries that follow:
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
Table: Admin
Table: Transport
(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);
(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;
(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
(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
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
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
(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';
E code - String
E_name String
Sal - Integer
City - String
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.
mycursor-mydb.cursor()
_____________________# Statement 2
______________________#Statement 3
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
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.
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.
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
Username: admin
Password: Shopping
Host: localhost
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:
Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)
Solution:
import mysql.connector as mysql
def AddAndDisplay():
mydb = mysql.connect(host="localhost", user="root", passwd="Pencil",
database="ITEMDB")
mycursor = mydb.cursor()
mydb.commit()
mycursor.execute("SELECT * FROM STATIONERY WHERE price > 120")
records = mycursor.fetchall()