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
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)- A78% (21)
- B4% (1)
- C4% (1)
- D15% (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 requirefuncto return a 4-character string, which would needfunc(4), notfunc(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 iffuncreturned 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.