Function overloading in Python

I am trying to use function overloading in Python, but I am getting an error that says “TypeError: add() takes 2 positional arguments but 3 were given.” Can anyone help me understand why this is happening and how to fix it? Here is an example of my code:

def add(a, b):
return a + b

def add(a, b, c):
return a + b + c

print(add(1, 2)) # should return 3
print(add(1, 2, 3)) # should return 6"
1 Like

Python doesn’t have function overloading. See https://www.educba.com/function-overloading-in-python/

You can’t do overloading but you can do something similar by just setting the default value to zero and then don’t use that parameter. For example:

def add(a, b, c=0):
return a + b + c

you could also have your function take a single list as a parameter, and be completely flexible about the size of the list. (course, in this simple case, that’s equivalent to the sum function, but the point remains).