Question 48 of 97
Q.What possible output from the given options is expected to be displayed when the following Python code is executed? import random Signal = ['RED', 'YELLOW', 'GREEN'] for K in range(2, 0, -1): R = random.randrange(K) print(Signal[R], end='#') (A) YELLOW # RED # (B) RED # GREEN # (C) GREEN # RED # (D) YELLOW # GREEN #
Puducherry CbseCBSE Class XII Board 2024MCQ· 1mImportance★★★★★
49% · 48/97 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The loop runs twice. random.randrange(2) (first pass) returns 0 or 1; random.randrange(1) (second pass) can only return 0. So the output is either RED#RED# or YELLOW#RED#. Option (A) YELLOW # RED # is one valid possibility.
Key ideas
range(2, 0, -1)generates2, then1(it stops before 0).random.randrange(stop)returns a random integer from 0 up tostop - 1(neverstopitself).- List indexing:
Signal[0]is 'RED',Signal[1]is 'YELLOW',Signal[2]is 'GREEN'. print(..., end='#')ends each output with#instead of a newline.
Trace
- K = 2:
R = random.randrange(2)returns 0 or 1. R = 0 printsRED#; R = 1 printsYELLOW#. - K = 1:
R = random.randrange(1)returns only 0, so it printsRED#. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.