🌐
Real Python
realpython.com › ref › builtin-exceptions › typeerror
TypeError | Python’s Built-in Exceptions – Real Python
>>> def safe_add(a, b): ... try: ... return a + b ... except TypeError: ... print(f"{type(a)} and {type(b)} are incompatible for addition.") ... return None ... >>> safe_add(5, 10) 15 >>> safe_add(5, "10") <class 'int'> and <class 'str'> are incompatible for addition. An example of when you may want to raise the exception: Language: Python ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - Although Python is dynamically ... between incompatible types raises a TypeError. For example, combining a string and an integer using the + operator is invalid....
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › python typeerror
Python TypeError | How to Avoid TypeError with Examples
April 13, 2023 - So in this way, we can avoid TypeError. ... In the above example, you can see that we have created two variables. One is holding an integer value, and another is holding a string or character value. Now we are trying to perform division between the variable and hold the result into the third variable and printing the result. But python will throw TypeError because an integer cannot be divided by string or character, the python was expecting integer value, so it throws TypeError.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
W3Schools
w3schools.com › python › ref_exception_typeerror.asp
Python TypeError Exception
You can handle the TypeError in a try...except statement, see the example below. Handling the TypeError in a try...except statement:
🌐
PythonForBeginners.com
pythonforbeginners.com › home › typeerror in python
TypeError in Python - PythonForBeginners.com
December 28, 2022 - Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module> myResult = myInt / myStr TypeError: unsupported operand type(s) for /: 'int' and 'str' Let us take another example, Suppose that we want to concatenate two lists.
🌐
Pronod's Blog
data-intelligence.hashnode.dev › handling-typeerror-in-python-guide
Understanding and Fixing Python TypeErrors - Pronod's Blog
September 13, 2024 - # Example: Concatenating a string with an integer result = "Hello" + 123 · This code will raise a TypeError because Python doesn't support concatenating a string with an integer.
🌐
Rollbar
rollbar.com › home › how to fix typeerror exceptions in python
How to Fix TypeError Exceptions in Python | Rollbar
In the above example, the string my_string is attempted to be added to an integer my_integer. Since addition cannot be performed between these two types, a TypeError is raised: File "test.py", line 3, in <module> my_result = my_integer + my_string TypeError: unsupported operand type(s) for +: 'int' and 'str' To avoid type errors in Python, the type of an object should be checked before performing an operation.
Published: October 1, 2022
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › typeError.html
Error Encyclopedia | Type Error
For example, let's see what happens when we try and add together two incompatible types: >>> 2 + "two" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' Because the plus operator (+) expected two numeric parameters, Python throws a TypeError, telling us that one of our parameters was of the incorrect type.
🌐
Tutorial Teacher
tutorialsteacher.com › python › error-types-in-python
Error Types in Python
>>> '2'+2 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> '2'+2 TypeError: must be str, not int
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
Traceback (most recent call last): File "<stdin>", line 2, in <module> raise TypeError('bad type') TypeError: bad type Add some information Add some more information >>> For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors.
🌐
Python Principles
pythonprinciples.com › blog › type-errors
Type Errors – Python Principles
For example, the following (wrong) code adds a string and an integer: ... Traceback (most recent call last): File "/tmp/pyrunnerAAUd0sg1/code.py", line 4, in print(a + b) TypeError: cannot concatenate 'str' and 'int' objects · Note that Python shows you the offending line.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
Add the string note to the exception’s notes which appear in the standard traceback after the exception string. A TypeError is raised if note is not a string.
🌐
PyTutorial
pytutorial.com › python-typeerror-causes-and-fixes
PyTutorial | Python TypeError: Causes and Fixes
April 23, 2026 - When you call a function with the wrong number or type of arguments, Python raises a TypeError. For example, the sum() function expects an iterable of numbers.
🌐
OpenPython
openpython.org › python-errors › typeerror
Python TypeError — What It Is and How to Fix It | OpenPython
age = 25 message = "I am " + age + " years old" # TypeError: can only concatenate str (not "int") to str ... age = 25 message = "I am " + str(age) + " years old" # Or use an f-string (preferred): message = f"I am {age} years old" print(message) ...
Top answer
1 of 2
8
@Liam Hayes (https://teamtreehouse.com/liamhayes) Hi! I have a note about @Steven Parker (https://teamtreehouse.com/stevenparker)'s example (especially the second one). When I was trying to wrap my head around this, I could not for the life of me understand why the built-in function for changing something to an int would give a ValueError with a string as opposed to a TypeError. Surely, it's expecting a number, right? Well, no. It isn't. The int() function takes either a number or a string. It can convert the string "21" to the integer 21, but it can't convert "dog" to a number. Thus, it's getting the right type, but it's still not a value that it can convert. This is when we get the ValueError. It's of the right type, but the value is such that it still can't be done. That being said, if we tried to send in something that was neither a string nor a number, it would have generated a TypeError as it is of the wrong type. Hope this helps! :sparkles: edited for additional note In your own custom made functions, you can pass in whatever you want, although ideally, you know what you're passing in. This is not true of built-in functions in Python. When in doubt, check the documentation for the function in question.
2 of 2
0
A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. Examples: passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. For more details, see the Exceptions page (https://docs.python.org/3/library/exceptions.html) of the Python documentation.
Top answer
1 of 2
2

You can use a try-except to catch the error, and throw for example another one:

def prefill(n,v):
    try:
        n = int(n)
    except ValueError:
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n

For example:

>>> prefill(3,1)
[1, 1, 1]
>>> prefill(2,"abc")
['abc', 'abc']
>>> prefill("1", 1)
[1]
>>> prefill(3, prefill(2,'2d'))
[['2d', '2d'], ['2d', '2d'], ['2d', '2d']]
>>> prefill("xyz", 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in prefill
ValueError: invalid literal for int() with base 10: 'xyz'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in prefill
TypeError: xyz is invalid

You do not per se need to specify an exception to raise. In case you want to re-raise the exception, simply writing raise is sufficient. You can furthermore specify a tuple of exceptions to catch, and make v optional here, for example:

def prefill(n,v=None):
    try:
        n = int(n)
    except (TypeError, ValueError):
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n
2 of 2
2

Use the raise keyword to raise an exception, rather than return it. raise is used to generate a new exception:

>>> raise TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

In this example I raised the TypeError by using the exception class directly. You can also create instances of the error like this:

>>> t=TypeError()
>>> raise t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

Doing it that way allows various properties to be set on the object before using raise. The problem posted includes this requirement:

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

That is an example of a situation where it is necessary to create an instance of the error and set a message property on it before using raise. That can still be done in one line:

>>> raise TypeError("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo

To catch exceptions, use a try-except block, rather than an if block:

x = 'hello, world!'
try:
    y = x / 2
except TypeError as e:
    e.args = (*e.args, str(x) + " is not valid")
    raise

This will raise an error:

TypeError: ("unsupported operand type(s) for /: 'str' and 'int'", 'hello, world! is not valid')

note that you can check the datatype of a variable using type():

>>> x = 5
>>> type(x)
<class 'int'>
>>> if type(x) == int:
...   print("it's an int")
...
it's an int

Also, the code sample could be simplified to:

    return [v for _ in range(n)]

🌐
TutorialsPoint
tutorialspoint.com › How-to-catch-TypeError-Exception-in-Python
How to catch TypeError Exception in Python?
A TypeError occurs in Python when we perform an operation on an object of an inappropriate type. For example, adding a string to an integer or calling a non-callable object. In this article, you will learn how to catch and handle TypeError exceptions
🌐
freeCodeCamp
freecodecamp.org › news › typeerror-int-object-is-not-callable-how-to-fix-in-python
Typeerror: int object is not callable – How to Fix in Python
July 18, 2022 - The code resulted in an error because the same sum has already been used as a variable name: kid_ages = [2, 7, 5, 6, 3] sum = 0 sum = sum(kid_ages) print(sum) Another example below shows how I tried to get the oldest within those kids with the ...
🌐
Medium
medium.com › @techwithpraisejames › types-of-errors-in-python-and-how-to-handle-them-fe8616257b52
Common Types of Errors in Python and How to Handle Them | by Praise James | Medium
August 7, 2025 - In this example, the addition operation is performed on an integer and a string, which would result in a TypeError. Type errors can also occur when you try to perform operations on objects that do not support the specific operation being attempted, ...