nerdexam
Python_Institute

PCEP-30-02 · Question #188

What is the expected output of the following code? def func(x): if x % 2 == 0: return 1 else: return print(func(func(2)) + 1)

The correct answer is D. The code is erroneous. Option D is correct because the code raises a TypeError at runtime: func(2) returns 1 (since 2 is even), then func(1) hits the else branch and returns None (a bare return in Python always returns None), and finally None + 1 causes a crash since you cannot add NoneType and int…

Question

What is the expected output of the following code? def func(x): if x % 2 == 0: return 1 else: return print(func(func(2)) + 1)

Options

  • ANone
  • B1
  • C2
  • DThe code is erroneous.

How the community answered

(47 responses)
  • A
    13% (6)
  • B
    4% (2)
  • C
    2% (1)
  • D
    81% (38)

Explanation

Option D is correct because the code raises a TypeError at runtime: func(2) returns 1 (since 2 is even), then func(1) hits the else branch and returns None (a bare return in Python always returns None), and finally None + 1 causes a crash since you cannot add NoneType and int.

  • A (None) is wrong because the code never silently produces None as output - the + 1 operation on None crashes before anything can be printed.
  • B (1) and C (2) are wrong for the same reason: the TypeError prevents the print from ever executing, so no numeric result is produced.

Memory tip: Whenever you see a bare return (no value) in Python, mentally substitute return None - then ask yourself what happens when that None is used in an arithmetic expression. If it's added, subtracted, or multiplied with a number, it's always a TypeError.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice