nerdexam
Python_Institute

PCEP-30-02 · Question #286

What is the expected output of the following code? def func(text, num): while num > 0: print(text) num = num - 1 func('Hello', 3)

The correct answer is D. An infinite loop. Option D is correct because num = num - 1 sits outside the while loop - it shares the same indentation level as the while statement rather than being indented beneath it. This means num is never decremented during the loop, so the condition num > 0 remains permanently True, and…

Question

What is the expected output of the following code? def func(text, num): while num > 0: print(text) num = num - 1 func('Hello', 3)

Options

  • A1 | Hello 2 | Hello
  • B1 | Hello
  • C1 | Hello 2 | Hello 3 | Hello
  • DAn infinite loop.

How the community answered

(34 responses)
  • A
    6% (2)
  • B
    12% (4)
  • C
    3% (1)
  • D
    79% (27)

Explanation

Option D is correct because num = num - 1 sits outside the while loop - it shares the same indentation level as the while statement rather than being indented beneath it. This means num is never decremented during the loop, so the condition num > 0 remains permanently True, and print(text) executes endlessly.

Options A, B, and C are all wrong for the same root reason: they assume the decrement actually runs on each iteration, which would correctly count down from 3 to 0 and print "Hello" three times - but that only happens if num = num - 1 is inside the loop body.

Memory tip: In Python, indentation IS logic. Whenever you see a while or for loop, visually trace a vertical line down from the loop's body - anything that "falls off" that line (returns to the loop's own indentation level) runs after the loop, not inside it. If the loop's counter update falls off that line, suspect an infinite loop.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice