PCEP-30-02 · Question #353
What is the expected result of running the following code? ``python def do_the_mess(parameter): global variable variable += parameter[0] return variable the_list = [x for x in range(2, 3)] variable…
The correct answer is A. The code prints 2. Option A is correct because range(2, 3) produces only one element - 2 - making the_list = [2]. The global variable declaration inside do_the_mess means the function modifies the outer variable (not a local copy), so variable += parameter[0] computes 0 + 2 = 2, and…
Question
def do_the_mess(parameter):
global variable
variable += parameter[0]
return variable
the_list = [x for x in range(2, 3)]
variable = 0
do_the_mess(the_list)
print(variable)
Options
- AThe code prints 2
- BThe code prints 1
- CThe code prints 0
- DThe code raises an unhandled exception.
How the community answered
(28 responses)- A75% (21)
- B7% (2)
- C4% (1)
- D14% (4)
Explanation
Option A is correct because range(2, 3) produces only one element - 2 - making the_list = [2]. The global variable declaration inside do_the_mess means the function modifies the outer variable (not a local copy), so variable += parameter[0] computes 0 + 2 = 2, and print(variable) reflects that change.
Why the distractors fail:
- B (prints 1): Confuses
range(2, 3)with something starting at 0 or 1;range(start, stop)starts atstart, not 0. - C (prints 0): Would be correct without the
globalkeyword - without it, the assignment would create a local variable and leave the outer one unchanged (or raise anUnboundLocalError). Theglobalstatement is the key detail here. - D (raises exception): No error occurs -
the_listis a valid one-element list, soparameter[0]is perfectly legal.
Memory tip: Think of global as "reach out and grab the real thing" - any modification inside the function travels back to the outer scope. And always parse range(a, b) as a half-open interval [a, b): it includes a and excludes b.
Community Discussion
No community discussion yet for this question.