Test Index

CBSE Class 12 Computer Science 2026 Paper Compartment Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 25 of 37
Marks: +1, -0
What possible output from the given options is expected to be displayed when the following code is executed ? Justify your answer.
import random
ITEMS={1:"PEN", 2: "ERASER", 3: "PENCIL"}
for i in range(len(ITEMS)):
print(ITEMS[random.randint(0,i)+1],end="*")
(A) PEN*PENCIL*PENCIL*
(B) PENCIL*PEN*ERASER*
(C) PEN*PENCIL*ERASER*
(D) PEN*ERASER*PEN*
Solution:  
Answer: (D) PEN*ERASER*PEN*
Justification:
len(ITEMS) = 3, so the loop runs for i = 0, 1, 2. random.randint(a, b) returns an integer from a to b, both included.
irandint(0, i)key = randint(0, i) + 1possible word
001PEN
10 or 11 or 2PEN or ERASER
20, 1 or 21, 2 or 3PEN, ERASER or PENCIL
So the first word must be PEN and the second word must be PEN or ERASER.
(A) and (C): second word PENCIL is impossible.
(B): first word PENCIL is impossible.
(D) PEN*ERASER*PEN*: first PEN (i = 0), second ERASER (i = 1), third PEN (i = 2): all allowed.
Each word is followed by * because of end="*".
Key point: As printed, the print() line is not indented under the for statement, which would give an IndentationError. The question intends it as the body of the loop:
for i in range(len(ITEMS)):
print(ITEMS[random.randint(0,i)+1],end="*")
© examsnet.com
Advertisements
Go to Question: