TryBugHunt

TypeError: unsupported operand type(s) for +: 'int' and 'str'

TypeError: unsupported operand type(s) for +: 'int' and 'str' in Python means you added a number and a string. Python will not guess whether you meant arithmetic or joining text, so convert one side.

PythonPattern: Type errors

How do I fix TypeError: unsupported operand type(s) for +: 'int' and 'str'?

TypeError: unsupported operand type(s) for +: 'int' and 'str' means you added a number and a string. Python will not guess whether you want maths or joined text. Text from input(), split() or a form stays a string, so convert it with int() or float() before adding, as in sum(int(v) for v in parts).

  1. 1. Print both typesPrint type() of each side of the + on the failing line. The message lists them left then right.
  2. 2. sum() over stringsInside sum(), the int is the starting 0. Convert items: sum(int(v) for v in values).
  3. 3. Convert at the inputWrap input() or form values with int() or float() where they enter the program, not halfway through.

What does TypeError: unsupported operand type(s) for +: 'int' and 'str' mean?

+ adds numbers and joins strings, never a mix. The message names the left and right types: an int on the left, a str on the right. Inside sum(), the int is sum's starting value 0 and the str is your data.

Why does TypeError: unsupported operand type(s) for +: 'int' and 'str' happen?

1. Summing text that looks like numbers

split() returns strings, even when they contain digits.

Breaks

total = sum("4,5,6".split(","))

Works

total = sum(int(v) for v in "4,5,6".split(","))

2. sum() over a dictionary of names

Iterating a dictionary yields its keys.

Breaks

total = sum({"a": 1, "b": 2})

Works

total = sum({"a": 1, "b": 2}.values())

3. Adding form input to a number

Everything from input() or a form is text.

Breaks

total = 0
total = total + form_value

Works

total = 0
total = total + int(form_value)

How to find it in your own code

Print type() of both sides on the failing line. Convert text to numbers where it enters the program, with int() or float(), rather than halfway through a calculation.

Try it: fix this bug

easy

concatenate_words(["code", "review"]) raises TypeError: unsupported operand type(s) for +: 'int' and 'str'.

def concatenate_words(words):
    return sum(words)
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all type errors →