Bird
0
0

Find the error in this polymorphic function and fix it:

medium📝 Debug Q14 of 15
Python - Polymorphism and Dynamic Behavior

Find the error in this polymorphic function and fix it:

def process(value):
    if isinstance(value, int):
        return value * 2
    elif isinstance(value, str):
        return value + value
    else:
        return value / 2

print(process('abc'))
print(process([1, 2, 3]))
ANo error; code runs fine
BError: Cannot divide list by 2; fix by handling list separately
CError: Missing return statement for int type
DError: Cannot multiply string by 2; fix by converting to int
Step-by-Step Solution
Solution:
  1. Step 1: Analyze input 'abc'

    String input returns 'abcabc' by concatenation, no error.
  2. Step 2: Analyze input [1, 2, 3]

    List input goes to else: value / 2, but dividing list by 2 causes TypeError.
  3. Step 3: Fix the error

    Need to add a check for list type or avoid dividing list by 2.
  4. Final Answer:

    Error: Cannot divide list by 2; fix by handling list separately -> Option B
  5. Quick Check:

    List / 2 causes error [OK]
Quick Trick: Check operations valid for each type [OK]
Common Mistakes:
  • Assuming all types support division
  • Not testing with different input types
  • Ignoring TypeError exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes