PromptHub
Python Beginner 11 views

Python ValueError

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

Explanation

ValueError occurs when a function receives an argument that has the right type but an invalid value. For example, int("abc") raises ValueError because "abc" is a string (correct type) but cannot be converted to an integer (invalid value). This differs from TypeError which occurs when the argument type itself is wrong. ValueError commonly happens with conversions, validations, and operations that have value constraints.

Common Causes

  • Invalid type conversion value
  • Value out of allowed range
  • Invalid format string
  • Value not in allowed set
  • Constraint violation

Solution

Validate input values before passing them to functions. Use try-except ValueError blocks to handle invalid values gracefully. Check value constraints (ranges, formats, allowed values) before operations. Use int(s, base=10) for safe integer parsing. For list operations like index(), check if the value exists first using the in operator. Use enum.Enum for restricted value sets.

Code Example

# ValueError from invalid conversion
age = int("abc")  # ValueError: invalid literal for int()

# Fix: validate before converting
def safe_int(value, default=0):
    try:
        return int(value)
    except ValueError:
        return default

age = safe_int("abc", 0)

# ValueError from list.index()
data = [1, 2, 3]
index = data.index(5)  # ValueError: 5 is not in list

# Fix: check first
if 5 in data:
    index = data.index(5)

# ValueError from math.sqrt of negative
import math
result = math.sqrt(-1)  # ValueError: math domain error

# Fix: check value first
if number >= 0:
    result = math.sqrt(number)
else:
    result = None

Error Information

Language

python

Difficulty

Beginner

Views

11

Related Errors