Editor

TypeError: add() takes 2 positional arguments but 3 were given

What it means

You called a function with more values than its definition has parameters. Python counts every value inside the brackets, and for a method it also counts the object itself, which arrives as self. That is why the numbers in the message can be one higher than what you typed.

1. Passing more arguments than the function accepts

This raises the error

Broken
def add(a, b):
return a + b
print(add(2, 3, 4))
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
TypeError: add() takes 2 positional arguments but 3 were given

The fix

Fixed
def add(a, b, c=0): # an optional third number
return a + b + c
print(add(2, 3, 4))
print(add(2, 3))
Output
9
5

The function now has a parameter for the third value, with a default so two-number calls still work. To accept any number of values, write def add(*nums) and return sum(nums).

Try fixing it yourself in the editor

2. A method that is missing `self`

This raises the error

Broken
class Dog:
def bark():
print('Woof!')
rex = Dog()
rex.bark()
Output
Traceback (most recent call last):
  File "<exec>", line 6, in <module>
TypeError: Dog.bark() takes 0 positional arguments but 1 was given

The fix

Fixed
class Dog:
def bark(self): # self receives the object
print('Woof!')
rex = Dog()
rex.bark()
Output
Woof!

rex.bark() really runs Dog.bark(rex), so Python passes the object in as the first argument. Every regular method needs a first parameter to receive it, called self by convention.

Try fixing it yourself in the editor

3. `__init__` does not list a value you pass to the class

This raises the error

Broken
class Dog:
def __init__(self):
self.name = 'Rex'
pet = Dog('Buddy')
print(pet.name)
Output
Traceback (most recent call last):
  File "<exec>", line 5, in <module>
TypeError: Dog.__init__() takes 1 positional argument but 2 were given

The fix

Fixed
class Dog:
def __init__(self, name):
self.name = name
pet = Dog('Buddy')
print(pet.name)
Output
Buddy

The values in Dog('Buddy') go to __init__, after self. Add a parameter for each value you pass when you create the object.

Try fixing it yourself in the editor

When you see this error, check

  • Count the values in your call and the parameters in the def line, remembering that a method's self counts as one.
  • Make sure every method inside a class has self as its first parameter.
  • If two functions share a name, the later def replaces the earlier one, so check you are calling the version you think.
  • To accept a flexible number of values, use *args in the definition.

All Python errors · How to read a traceback · Step through your code