Test Index

Functions in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 5 of 23
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*
[CBSE 2026 Compartment]
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: Written exactly as shown, the print() line is not indented under the for statement, so Python stops with an IndentationError (expected an indented block). With print() as the body of the loop, the code runs as worked out above:
for i in range(len(ITEMS)):
print(ITEMS[random.randint(0,i)+1],end="*")
© examsnet.com
Advertisements
Go to Question: