# How to Fix Python TypeError: unsupported operand type

The TypeError: unsupported operand type(s) occurs when you try to perform an operation on values of incompatible types. This commonly happens with arithmetic operations, string concatenation, and function arguments.

Error Patterns

Arithmetic Type Errors

text
Traceback (most recent call last):
  File "app.py", line 3, in <module>
    result = "42" + 10
TypeError: can only concatenate str (not "int") to str
text
Traceback (most recent call last):
  File "app.py", line 5, in <module>
    result = "100" / 2
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Comparison Type Errors

text
Traceback (most recent call last):
  File "app.py", line 4, in <module>
    if user_input > 100:
TypeError: '>' not supported between instances of 'str' and 'int'

Function Argument Type Errors

text
Traceback (most recent call last):
  File "app.py", line 8, in <module>
    calculate_average("10", "20", "30")
TypeError: unsupported operand type(s) for +: 'str' and 'int'

NoneType Arithmetic

text
Traceback (most recent call last):
  File "app.py", line 6, in <module>
    total = value + 10
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Common Causes

  1. 1.String instead of number - User input returns string, not int
  2. 2.None value in arithmetic - Function returned None instead of number
  3. 3.Mixed types in operations - Adding string to int, list to dict
  4. 4.Wrong argument type - Passing string to function expecting int
  5. 5.Implicit conversion missing - Python doesn't auto-convert types
  6. 6.API response handling - JSON returns strings, not numbers

Diagnosis Steps

Step 1: Check Variable Types

```python # Debug: print types before operation value1 = get_value1() value2 = get_value2()

print(f"value1 type: {type(value1)}, value: {value1}") print(f"value2 type: {type(value2)}, value: {value2}")

# This will reveal the type mismatch result = value1 + value2 ```

Step 2: Trace Data Flow

```python # Find where wrong type comes from def process_data(input_value): print(f"Input type: {type(input_value)}, value: {input_value}") # Process... return result

# Check each transformation step1 = read_input() print(f"After read: {type(step1)}") step2 = transform(step1) print(f"After transform: {type(step2)}") ```

Step 3: Use Type Hints and Static Analysis

```python # Type hints help catch errors before runtime def calculate_total(price: float, quantity: int) -> float: return price * quantity

# Static analyzers like mypy will catch: # calculate_total("10.99", 5) # Error: str passed to float parameter ```

Solutions

Solution 1: Convert String to Number

```python # Problem: String input user_input = "42" result = user_input + 10 # TypeError

# Fix: Convert to int user_input = "42" result = int(user_input) + 10 # 52

# Fix: Convert to float for decimals price = "19.99" total = float(price) * 2 # 39.98

# Handle invalid conversion try: value = int(user_input) except ValueError: print(f"Cannot convert '{user_input}' to integer") ```

Solution 2: Convert Number to String

```python # Problem: Concatenating string and number age = 25 message = "Age: " + age # TypeError

# Fix: Convert to string message = "Age: " + str(age) # "Age: 25"

# Better: Use f-strings message = f"Age: {age}" # "Age: 25"

# Or use format message = "Age: {}".format(age) ```

Solution 3: Handle None Values

```python # Problem: None in arithmetic def get_discount(price): if price > 100: return price * 0.1 # Returns None if price <= 100

final_price = price - get_discount(price) # TypeError if None

# Fix: Provide default discount = get_discount(price) or 0 final_price = price - discount

# Or check explicitly discount = get_discount(price) if discount is not None: final_price = price - discount else: final_price = price ```

Solution 4: Use Proper Comparison Types

```python # Problem: Comparing string and int user_input = input("Enter a number: ") # Returns string if user_input > 100: # TypeError in Python 3 print("Large!")

# Fix: Convert before comparison user_input = int(input("Enter a number: ")) if user_input > 100: print("Large!")

# Or use try/except try: value = int(user_input) if value > 100: print("Large!") except ValueError: print("Invalid number") ```

Solution 5: Fix Function Arguments

```python # Problem: Wrong argument types def calculate_average(numbers): return sum(numbers) / len(numbers)

result = calculate_average("12345") # TypeError

# Fix: Pass correct type result = calculate_average([1, 2, 3, 4, 5]) # 3.0

# Or convert inside function def calculate_average(numbers): if isinstance(numbers, str): numbers = [int(c) for c in numbers] return sum(numbers) / len(numbers) ```

Solution 6: Handle API Response Types

```python import requests

response = requests.get("https://api.example.com/data") data = response.json()

# Problem: JSON returns strings price = data["price"] # "99.99" as string quantity = data["quantity"] # "5" as string total = price * quantity # TypeError

# Fix: Convert after parsing price = float(data["price"]) quantity = int(data["quantity"]) total = price * quantity

# Or use Pydantic for automatic conversion from pydantic import BaseModel

class Product(BaseModel): price: float quantity: int

product = Product(**data) total = product.price * product.quantity ```

Solution 7: Fix List/Dict Operations

```python # Problem: Adding list and dict items = [1, 2, 3] config = {"key": "value"} result = items + config # TypeError

# Fix: Extend list with dict keys or values items.extend(config.keys()) # [1, 2, 3, "key"] # Or items.extend(config.values()) # [1, 2, 3, "value"] # Or combine as dict combined = {"items": items, "config": config} ```

Solution 8: Use Polymorphic Operations

```python # Problem: Different types need different handling def multiply(a, b): return a * b # Works for numbers, not mixed types

multiply(5, "x") # "xxxxx" (string repetition) multiply("5", 3) # TypeError

# Fix: Convert explicitly def multiply(a, b): a = float(a) if isinstance(a, str) else a b = float(b) if isinstance(b, str) else b return a * b ```

Common Type Conversion Patterns

```python # Safe conversion functions def to_int(value, default=0): """Convert to int with default fallback.""" try: return int(value) except (ValueError, TypeError): return default

def to_float(value, default=0.0): """Convert to float with default fallback.""" try: return float(value) except (ValueError, TypeError): return default

def to_str(value, default=""): """Convert to string with default fallback.""" if value is None: return default return str(value)

# Usage price = to_float(user_input, default=0.0) quantity = to_int(config.get("quantity"), default=1) ```

Type Checking Best Practices

```python from typing import Union, Optional

# Use type hints def process( value: Union[int, float, str], multiplier: Optional[int] = None ) -> float: # Convert to number if isinstance(value, str): num = float(value) else: num = float(value)

# Apply multiplier if provided if multiplier is not None: num *= multiplier

return num

# Runtime type checking def safe_divide(a, b): if not isinstance(a, (int, float)): raise TypeError(f"Expected number, got {type(a)}") if not isinstance(b, (int, float)): raise TypeError(f"Expected number, got {type(b)}") if b == 0: raise ZeroDivisionError("Cannot divide by zero") return a / b ```

Prevention Tips

  1. 1.Use type hints and run mypy/pyright for static analysis
  2. 2.Validate user input before processing
  3. 3.Handle None explicitly in all functions
  4. 4.Convert types at boundaries (API calls, user input, file reads)
  5. 5.Use Pydantic for automatic type coercion

```python # Example: Input validation decorator from functools import wraps

def validate_types(*types): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for i, (arg, expected_type) in enumerate(zip(args, types)): if not isinstance(arg, expected_type): raise TypeError( f"Argument {i} must be {expected_type}, got {type(arg)}" ) return func(*args, **kwargs) return wrapper return decorator

@validate_types(int, int) def add(a, b): return a + b ```

  • ValueError - Correct type but invalid value (e.g., int("abc"))
  • AttributeError - Object missing an attribute
  • TypeError: takes exactly N arguments - Wrong number of arguments
  • TypeError: 'type' object is not subscriptable - Generics in older Python