liveBook · Manning

ValueError

As explained in Python How-To

ValueError is the Python exception raised when an operation receives an argument of an appropriate type but an inappropriate value.

ValueError occurs when an operation receives an argument of the right type but an unsuitable value. A common case is converting a numeric-looking string whose contents are invalid: int("3#") receives a string but cannot interpret its value as an integer. section 12.3

Handling invalid task data

A task parser can catch the conversion failure explicitly: try: urgency = int(urgency_str) except ValueError as ex: print(f"Couldn't cast the number. Description: {ex}") return None For input "Laundry,3#", Python reports: invalid literal for int() with base 10: '3#'. A user-facing application could display a warning and request corrected data instead of stopping. section 12.3 section 12.3.4

ValueError also appears when valid operations cannot use a requested value:

  • list.remove(item) raises ValueError when the item is absent. section 3.1.1
  • sequence.index(item) raises ValueError when no matching item exists. section 4.3.5
  • Handle the specific exception rather than using a broad catch; run the potentially failing operation during development to identify the appropriate exception. section 12.3.6
Listing 12.12 Creating a variable from the exception
def process_task_string6(text):
    title, urgency_str = text.split(",")
    try:
        urgency = int(urgency_str)
    except ValueError as ex:
        print(f"Couldn't cast the number. Description: {ex}")
        return None
    task = Task(title, urgency)
    return task

Shows a complete task-processing function that catches ValueError, binds it to ex, reports its details, and returns None. section 12.3.4

How Python How-To covers it

How deep it goes
Explains invalid conversion, caught exception details, explicit exception selection, and EAFP versus LBYL handling.
Examples
Uses corrupted task data, int("3#"), list.remove, and sequence.index to demonstrate invalid values.
What it assumes
Assumes string-to-integer conversion and introduces explicit exception handling for operations requiring specific input values.
What you can do after
Diagnose/debug with it by running risky operations, identifying ValueError, catching it explicitly, and presenting useful feedback.
How it connects
Connects ValueError with exception handling, int conversion, try...except, EAFP, LBYL, lists, and sequence indexing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.