nerdexam
Python_Institute

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

What is the expected result of running the following code?
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)
  • A
    75% (21)
  • B
    7% (2)
  • C
    4% (1)
  • D
    14% (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 at start, not 0.
  • C (prints 0): Would be correct without the global keyword - without it, the assignment would create a local variable and leave the outer one unchanged (or raise an UnboundLocalError). The global statement is the key detail here.
  • D (raises exception): No error occurs - the_list is a valid one-element list, so parameter[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.

Full PCEP-30-02 Practice