0% found this document useful (0 votes)
47 views25 pages

Class 12 CS PYQs Compilation Part-1 by Nitin Paliwal

Uploaded by

nirjaraj798
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)
47 views25 pages

Class 12 CS PYQs Compilation Part-1 by Nitin Paliwal

Uploaded by

nirjaraj798
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/ 25

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

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy