nerdexam
Python_Institute

PCEP-30-02 · Question #219

What is the expected output of the following code? ``python def func(n): s = '**' for i in range(n): s += s yield s for x in func(2): print(x, end='') ``

The correct answer is C. **. Option C is correct because func is a generator function (it contains yield), so calling func(2) does not execute the body immediately - it returns a lazy generator object. When the outer for x in func(2) loop drives the generator, s holds its initial value '' at the point…

Question

What is the expected output of the following code?
def func(n):
 s = '**'
 for i in range(n):
 s += s
 yield s

for x in func(2):
 print(x, end='')

Options

  • A
  • B
  • C**
  • D..

How the community answered

(46 responses)
  • A
    2% (1)
  • B
    7% (3)
  • C
    78% (36)
  • D
    13% (6)

Explanation

Option C is correct because func is a generator function (it contains yield), so calling func(2) does not execute the body immediately - it returns a lazy generator object. When the outer for x in func(2) loop drives the generator, s holds its initial value '**' at the point yield s is reached (the s += s modification and the yield execute at the same indentation level outside the inner for block, meaning yield fires once with the unmodified s), so only '**' is printed.

Why the distractors fail: A (****) incorrectly assumes s += s runs once before the yield, doubling the string; B (***) has no valid execution path - you can't produce an odd number of * by doubling a 2-character string; D (..) confuses the asterisk character with a period, a simple misread.

Memory tip: For generators, always trace what s equals at the exact line the yield appears, not what it equals by the end of the function - generators pause and hand off the value right at yield, so earlier or later mutations don't matter.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice