🔧 Error Fixes
· 1 min read

Python ValueError: Invalid Literal for int() — How to Fix It


ValueError: invalid literal for int() with base 10: 'hello'

You’re trying to convert a string to a number, but the string isn’t a valid number.

Fix 1: Validate before converting

user_input = input("Enter a number: ")  # User types "hello"

# ❌ Crashes if input isn't a number
number = int(user_input)  # ValueError!

# ✅ Validate first
if user_input.isdigit():
    number = int(user_input)
else:
    print("Please enter a valid number")

Fix 2: Use try/except

try:
    number = int(user_input)
except ValueError:
    number = 0  # Default value
    print("Invalid number, using 0")

Fix 3: Strip whitespace and newlines

# ❌ Hidden whitespace
value = "42\n"
number = int(value)  # ValueError!

# ✅ Strip first
number = int(value.strip())  # 42

Fix 4: Handle floats

# ❌ int() can't parse floats directly
number = int("3.14")  # ValueError!

# ✅ Convert through float first
number = int(float("3.14"))  # 3
📘