Bird
Raised Fist0

What is the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Polymorphism and Dynamic Behavior

What is the output of this code?

def operate(x, y):
    if isinstance(x, str) and isinstance(y, str):
        return x + y
    elif isinstance(x, int) and isinstance(y, int):
        return x * y
    else:
        return None

print(operate('Hi', 'There'))
print(operate(3, 4))
print(operate('Hi', 4))

A'HiThere'\n7\nNone
B'HiThere'\n12\nNone
C'HiThere'\n12\n'Hi4'
DError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze function behavior for string inputs

    For two strings, it concatenates: 'Hi' + 'There' = 'HiThere'.
  2. Step 2: Analyze function behavior for integer inputs

    For two integers, it multiplies: 3 * 4 = 12.
  3. Step 3: Analyze mixed type inputs

    For 'Hi' and 4, types differ, so function returns None.
  4. Final Answer:

    'HiThere'\n12\nNone -> Option B
  5. Quick Check:

    Polymorphic function output matches 'HiThere'\n12\nNone [OK]
Quick Trick: Check input types to predict output in polymorphic functions [OK]
Common Mistakes:
MISTAKES
  • Assuming addition works for string and int
  • Mistaking multiplication for addition
  • Expecting error instead of None

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes