Brainlag
  1. Library
  2. Debugging
  3. Python

TypeErrorWhat is a TypeError?

A TypeError means an operation got the wrong kind of value, like adding a number to text or calling something that is not a function.

Python5 min

What TypeError means

Output
TypeError: can only concatenate str (not "int") to str

Every value has a type: text (str), whole numbers (int), lists, None and so on. A TypeError means a line tried to do something that does not make sense for the types it was given. Here, + was asked to glue text to a number, and Python will not guess whether you meant maths or text.

The usual causes:

  • Text and numbers mixed. "Score: " + 10. Use an f-string or str(10).
  • A number that is really text. input() always gives a string, so "5" + 1 fails.
  • A None where a value should be. A function that prints instead of returning gives back None.

How to find it

Read the last line: it names the operation and the types involved, like str and int. Go to the line number in the traceback and look at each value used there. Ask what type each one really is, not what you meant it to be. Printing type(x) just above that line settles it.

Run it: text plus a number

Press Run and read the error from the bottom up.

main.py to run
coins = 40
print("Coins: " + coins)

The coin counter that crashes

This should print You have 55 coins. Fix it without changing the numbers.

exercise_1.py to run
coins = 40
bonus = 15
print("You have " + coins + bonus + " coins")

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.