Test Index
CBSE Class 12 Computer Science 2026 Paper Compartment
© 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 randomITEMS={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.
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:
random.randint(a, b) returns an integer from a to b, both included.| i | randint(0, i) | key = randint(0, i) + 1 | possible word |
|---|---|---|---|
| 0 | 0 | 1 | PEN |
| 1 | 0 or 1 | 1 or 2 | PEN or ERASER |
| 2 | 0, 1 or 2 | 1, 2 or 3 | PEN, ERASER or PENCIL |
for i in range(len(ITEMS)): print(ITEMS[random.randint(0,i)+1],end="*")
© examsnet.com
Go to Question: