English

Write the overloaded function definitions of add()- on adds two numbers and other concatenates two strings.

Advertisements
Advertisements

Question

Write the overloaded function definitions of add()- on adds two numbers and other concatenates two strings.

Code Writing
Advertisements

Solution

Python cannot define two separate overloaded functions with the same name. However, the same add() function can perform both operations because + is polymorphic.

def add(a, b):
    return a + b  # Adds numbers or concatenates strings

print(add(10, 20))
print(add("Hello ", "World"))

30
Hello World

Here, add() is a single function; it is not traditional function overloading in Python.

shaalaa.com
  Is there an error in this question or solution?
Chapter 2: Concept of Object Oriented Programming - EXCERCISE [Page 37]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 2 Concept of Object Oriented Programming
EXCERCISE | Q 12. | Page 37
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×