How to Fix Python TypeError: unsupported operand type(s)
In this tutorial, you'll learn about How to Fix Python TypeError: unsupported operand type(s). We cover key concepts, practical examples, and best practices.
The Problem
You see TypeError: unsupported operand type(s) for +: 'int' and 'str' when trying to use an operator like +, -, *, or / between incompatible types such as an integer and a string.
Quick Fix
Step 1: Identify the mismatched types
Run a minimal reproduction to see which types are involved:
python3 -c "print(1 + '2')"
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The error shows int and str as the conflicting types.
Step 2: Convert one operand to match the other
If you need integer addition, convert the string to int:
python3 -c "print(1 + int('2'))"
3
If you need string concatenation, convert the int to string:
python3 -c "print(str(1) + '2')"
12
Step 3: Fix the variable in your code
Check where the mismatched value originates:
user_input = input("Enter a number: ")
result = user_input + 10
input() always returns a string. Cast it:
user_input = int(input("Enter a number: "))
result = user_input + 10
Step 4: Debug with type checking
Use type() and print() to find where the type diverges:
python3 -c "
x = '100'
y = 200
print(type(x), type(y))
"
<class 'str'> <class 'int'>
Alternative Solutions
Use type hints to catch mismatches early
Add type annotations to function parameters so mypy catches mismatches before runtime:
def add(a: int, b: int) -> int:
return a + b
Validate types at runtime
Raise a clear error when types do not match:
def safe_add(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError(f"Expected numeric types, got {type(a).__name__} and {type(b).__name__}")
return a + b
Common Mistakes to Avoid
Forgetting that input() returns a string. Always cast user input when performing arithmetic. Ages, quantities, and prices from forms arrive as strings.
Assuming all values in a list have the same type. A list like [1, "2", 3] raises a TypeError when you sum or compare elements. Use list comprehension with int() conversion.
Using + with None. If a variable is None and you try to concatenate it with a string, Python raises TypeError: can only concatenate str (not "NoneType") to str. Check for None before concatenation.
Mixing bytes and str in Python 3. Reading a binary file produces bytes, which cannot be concatenated with strings without decoding: data.decode("utf-8") + " suffix".
Pro Tips
Use mypy for static type checking. Run mypy on your codebase to catch type mismatches before runtime. Configure it in pyproject.toml with strict = true for maximum coverage.
Use f-strings for safe string formatting. Instead of concatenating with +, use f-strings which call __format__ and handle type conversion automatically: f"Result: {value}".
Check types with assert during development. Add assert isinstance(value, int) in critical code paths to catch type errors early in testing.
Prevention
- Always cast user input with
int()orfloat()before numeric operations. - Use
type()orisinstance()to validate variable types before operations. - Enable a type checker like
mypyto catch type mismatches during development.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro