0
0
Pythonprogramming~5 mins

Polymorphism through functions in Python

Choose your learning style9 modes available
Introduction

Polymorphism lets one function work with different types of data easily. It helps write simple and flexible code.

When you want one function to handle different kinds of inputs, like numbers or text.
When you want to use the same function name but do different things based on input type.
When you want to make your code easier to expand without changing existing functions.
When you want to write cleaner code that avoids repeating similar functions for each data type.
Syntax
Python
def function_name(parameter):
    # code that works with different types of parameter
    if isinstance(parameter, int):
        # do something for int
        pass
    elif isinstance(parameter, str):
        # do something for str
        pass
    else:
        # default action
        pass
You can check the type of input inside the function using isinstance().
The same function name can handle different input types by using conditions.
Examples
This function prints differently based on whether the input is a number or text.
Python
def show(value):
    if isinstance(value, int):
        print(f"Number: {value}")
    elif isinstance(value, str):
        print(f"Text: {value}")
    else:
        print("Unknown type")
This simple function adds two inputs. It works for numbers or strings (concatenation).
Python
def add(a, b):
    return a + b
Sample Program

This program shows how one function describe can handle different data types and print messages accordingly.

Python
def describe(item):
    if isinstance(item, int):
        print(f"This is an integer: {item}")
    elif isinstance(item, str):
        print(f"This is a string: '{item}'")
    elif isinstance(item, list):
        print(f"This is a list with {len(item)} items")
    else:
        print("Unknown type")

# Test the function with different types
describe(10)
describe("hello")
describe([1, 2, 3])
describe(3.14)
OutputSuccess
Important Notes

Polymorphism through functions helps keep code simple and easy to read.

Using isinstance() is a common way to check input types inside a function.

Python also supports polymorphism naturally with operators like + working on numbers and strings.

Summary

Polymorphism lets one function work with many data types.

Use isinstance() inside functions to handle different types.

This makes your code flexible and easier to maintain.