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
Traceback (most recent call last): File "<exec>", line 4, in <module> TypeError: add() takes 2 positional arguments but 3 were given
The fix
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).
2. A method that is missing `self`
This raises the error
Traceback (most recent call last): File "<exec>", line 6, in <module> TypeError: Dog.bark() takes 0 positional arguments but 1 was given
The fix
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.
3. `__init__` does not list a value you pass to the class
This raises the error
Traceback (most recent call last): File "<exec>", line 5, in <module> TypeError: Dog.__init__() takes 1 positional argument but 2 were given
The fix
Buddy
The values in Dog('Buddy') go to __init__, after self. Add a parameter for each value you pass when you create the object.
When you see this error, check
- Count the values in your call and the parameters in the
defline, remembering that a method'sselfcounts as one. - Make sure every method inside a class has
selfas its first parameter. - If two functions share a name, the later
defreplaces the earlier one, so check you are calling the version you think. - To accept a flexible number of values, use
*argsin the definition.
Related errors
All Python errors · How to read a traceback · Step through your code