Bird
Raised Fist0

Write a polymorphic function describe that returns:

hard🚀 Application Q8 of Q15
Python - Polymorphism and Dynamic Behavior

Write a polymorphic function describe that returns:
- "Number: <value>" if input is int or float
- "Text: <value>" if input is str
- "List of length <length>" if input is list
- "Unknown" otherwise

What will describe([1, 2, 3]) return?

A"List of length 3"
B"List of length [1, 2, 3]"
C"Unknown"
D"Number: [1, 2, 3]"
Step-by-Step Solution
Solution:
  1. Step 1: Understand function behavior for list input

    For list input, function returns 'List of length ' plus length of list.
  2. Step 2: Calculate length of [1, 2, 3]

    Length is 3, so output is 'List of length 3'.
  3. Final Answer:

    "List of length 3" -> Option A
  4. Quick Check:

    Polymorphic describe returns list length string for list input [OK]
Quick Trick: Use isinstance and len() to handle lists in polymorphic functions [OK]
Common Mistakes:
MISTAKES
  • Returning list itself instead of length
  • Confusing list with string
  • Returning Unknown for list input

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes