Python Principles

Python TypeError

A TypeError means that you're trying to combine values of different types that are not compatible.

For example, the following (wrong) code adds a string and an integer:

a = "1"
b = 2
print(a + b)

This causes an error, because you cannot add integers to strings:

Traceback (most recent call last):
  File "/tmp/pyrunnerAAUd0sg1/", line 4, in
    print(a + b)
TypeError: cannot concatenate 'str' and 'int' objects

Note that Python shows you the offending line. Pay careful attention to that line.

Fixing a TypeError

You typically fix a TypeError by casting your value(s) to the correct type.

In the example above, if you want to add the two numbers as integers, you'll have to cast the one that is a string:

print(int(a) + b)

If you instead want to concatenate the two as strings, you must cast the number to a string:

print(a + str(b))

In general, to fix a TypeError, think carefully about the types of the values in the line that Python highlighted for you. The types are not compatible. So decide which types you really want, then use casts.