Test Index

CBSE Class 12 Computer Science 2025 Paper Set 4 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 ?
import random
Cards=["Heart","Spade","Club","Diamond"]
for i in range(2):
print(Cards[random.randint(1,i+2)],end="#")
(A) Spade#Diamond#
(B) Spade#Heart#
(C) Diamond#Club#
(D) Heart#Spade#
Solution:  
Concept:
random.randint(a, b) returns a random integer from a to b, both included. The list indices are: 0 = Heart, 1 = Spade, 2 = Club, 3 = Diamond.
Possible values in each iteration:
irandint(1, i+2)Possible indexPossible card printed
0randint(1, 2)1 or 2Spade or Club
1randint(1, 3)1, 2 or 3Spade, Club or Diamond
Index 0 is never generated, so Heart can never be printed, and Diamond can be printed only in the second iteration.
Checking the options:
(A) Spade#Diamond#: Spade (index 1) first, Diamond (index 3) second. Possible.
(B) Spade#Heart#: Heart needs index 0. Not possible.
(C) Diamond#Club#: Diamond needs index 3 in the first iteration, where the maximum is 2. Not possible.
(D) Heart#Spade#: Heart needs index 0. Not possible.
Answer:
(A) Spade#Diamond#
© examsnet.com
Advertisements
Go to Question: