πŸ”§ 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
πŸ“˜