nerdexam
Python_Institute

PCEP-30-02 · Question #164

What is the expected output of the following code? ``python def func(num): res = '' for _ in range(num): res += '*' return res for x in func(2): print(x, end='') ``

The correct answer is A. ****. The stated correct answer (A) appears to be an error in this question - the actual output is `, making C correct.* Here is the accurate explanation: func(2) iterates range(2) times, appending one '' per iteration, and returns the string '*'. The outer for x in func(2): then…

Question

What is the expected output of the following code?
def func(num):
 res = ''
 for _ in range(num):
 res += '*'
 return res

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

Options

  • A
  • BThe code is erroneous.
  • C**
  • D

How the community answered

(27 responses)
  • A
    78% (21)
  • B
    4% (1)
  • C
    4% (1)
  • D
    15% (4)

Explanation

The stated correct answer (A) appears to be an error in this question - the actual output is **, making C correct.

Here is the accurate explanation:

func(2) iterates range(2) times, appending one '*' per iteration, and returns the string '**'. The outer for x in func(2): then iterates over that string character by character - Python strings are iterable sequences - yielding '*' twice. Each print(x, end='') outputs one star without a newline, so the final output is **.

  • A (****) is wrong - this would require func to return a 4-character string, which would need func(4), not func(2).
  • B (erroneous) is wrong - the code is syntactically valid Python (assuming standard indentation); it runs without error.
  • D (*) is wrong - this would only happen if func returned a single-character string, i.e., func(1).

Memory tip: When you see for x in some_string:, remember Python iterates strings character by character - so always trace what string the function returns, count its length, and that tells you exactly how many iterations the outer loop runs.

Exam note: If this question appears on an actual exam with A marked correct, flag it - it is incorrect based on standard Python semantics.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice