Test Index
Functions in Python
© 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 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*[CBSE 2026 Compartment]
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: 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:
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: