🔧 Error Fixes
· 1 min read

Python ValueError — How to Fix It


ValueError: invalid literal for int() with base 10: 'abc'
ValueError: too many values to unpack
ValueError: list.remove(x): x not in list

A function received an argument of the correct type but an inappropriate value.

Fix 1: Invalid Conversion

# ❌ Converting non-numeric string to int
num = int("abc")  # 💥

# ✅ Validate first
user_input = "abc"
if user_input.isdigit():
    num = int(user_input)
else:
    print("Not a number")

# ✅ Or use try/except
try:
    num = int(user_input)
except ValueError:
    num = 0  # Default

Fix 2: Too Many / Too Few Values to Unpack

# ❌ Wrong number of variables
a, b = [1, 2, 3]  # 💥 Too many values
a, b, c = [1, 2]  # 💥 Not enough values

# ✅ Match the count
a, b, c = [1, 2, 3]

# ✅ Or use * to capture extras
a, *rest = [1, 2, 3]  # a=1, rest=[2, 3]

Fix 3: Item Not in List

# ❌ Removing item that doesn't exist
items = [1, 2, 3]
items.remove(5)  # 💥

# ✅ Check first
if 5 in items:
    items.remove(5)

Fix 4: Invalid Date/Time

# ❌ Invalid date
from datetime import date
d = date(2026, 13, 1)  # 💥 Month 13

# ✅ Validate input
month = 13
if 1 <= month <= 12:
    d = date(2026, month, 1)

Fix 5: math.sqrt of Negative Number

# ❌ Square root of negative
import math
math.sqrt(-1)  # 💥

# ✅ Check or use cmath
if x >= 0:
    result = math.sqrt(x)

# For complex numbers
import cmath
result = cmath.sqrt(-1)  # 1j
📘