Python ValueError – Tutorial with Examples

Python ValueError - Tutorial with Examples

When working with Python, you are likely going to encounter errors. One of the most common errors that you will come across is the ValueError. It occurs when you try to assign or pass an argument to a function with an inappropriate value. In this tutorial, you will learn what a ValueError is and how to handle it in your code with some practical examples.

Understanding ValueError

ValueError is a built-in exception in Python. It is raised when an operation or function receives an argument that has the right type but an inappropriate or invalid value. Whenever the argument or the input you provide to a function doesn’t match what is expected, you’ll get a ValueError.

The ValueError can be raised by several reasons. Here are some possible causes behind a ValueError exception:

  • You provide incorrect data type values to functions which expect input data of a different data type
  • You’re trying to convert a string to a numeric type data like integer or float using the int(), float() method(s) and the string has characters other than numbers
  • You try to slice a log of text using incorrect index values or out-of-range index values
  • You provide invalid arguments to the built-in functions like max(), list() etc.

Examples of ValueError

Example 1: Invalid Argument

In this example, we create a function that accepts an integer and prints it. We then call the function with a string argument, which raises a ValueError because the function expects an integer.

<span class="code-comment"># Define the function</span>
def print_number(num):
    print(num)

<span class="code-comment"># Call the function with a string argument</span>
print_number('hello')

When you run the above code, you will encounter a ValueError stating that the function expects an integer:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in print_number
ValueError: invalid literal for int() with base 10: 'hello'

In this example, the input (‘hello’) is a string and not an integer, so Python raises a ValueError exception. To fix this error, we need to pass an integer to the function, like so:

<span class="code-comment"># Call the function with a proper argument</span>
print_number(5)

Example 2: Invalid Argument Type

In this example, we have defined a function called ‘add’. This function takes in 2 parameters which should contain floating-point numbers but let’s say I provide the string ‘hello’ as one of the parameters. This raises an error in python as it expects the parameter “b” to be a float.

<span class="code-comment"># Define the function</span>
def add(a, b):
    return a + b

<span class="code-comment"># Call the function with an invalid argument type</span>
add(3.14, 'hello')

When you run the above code, you will encounter a ValueError stating that the function expects the input to be a float:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in add
TypeError: unsupported operand type(s) for +: 'float' and 'str'

This error occurs when you try to add two variables of different types (float and string, in this case). This can be fixed by changing the type of the second argument to float:

<span class="code-comment"># Call the function with proper argument types</span>
add(3.14, 1.2)

Example 3: Slicing Error

In this example, we create a string variable ‘string_variable’ that contains a sentence. We want to extract the three characters between the 10th and 13th characters using Python string slicing. When we attempt to slice the string with incorrect indices, it triggers a ValueError.

<span class="code-comment"># Define the string variable</span>
string_variable = 'This is a sentence.'

<span class="code-comment"># Extract slice with incorrect indices causing ValueError</span>
new_string = string_variable[10:8]

When you execute the above code, you will encounter a ValueError stating that the indices to slice are out of range:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: slice indices must be integers or None or have an __index__ method

To fix this error, we need to set the correct values for the indices:

<span class="code-comment"># Extract slice with correct indices</span>
new_string = string_variable[10:13]

Handling ValueError

When you encounter a ValueError, the first step is to examine the error message carefully to identify the cause of the error. Once you understand the source of the error, you can implement some methods to handle the ValueError. Below are some ways of handling the ValueError:

  • Make sure that you’re passing the right type of argument to the function
  • Perform input validation checks to ensure that the user inputs the right data type and form
  • Try to pre-process the input data to make it appropriate for the function
  • Wrap the code block that could trigger a ValueError in a try… except statement

Example: Using Try…Except Blocks

In this example, we create a function called divide that accepts two numbers and returns the division of the two numbers. We then catch the ValueError that is raised whenever the user attempts to divide by 0.

<span class="code-comment"># Define the function</span>
def divide(numerator, denominator):
    try:
        quotient = numerator / denominator
        return quotient
    except ValueError as error:
        print(f"Encountered ValueError {error}")

<span class="code-comment"># Call the function with 0 as denominator</span>
print(divide(10, 0))

<span class="code-comment"># Call the function with a non-zero denominator</span>
print(divide(10, 2))

When you run the above code, you will encounter a ValueError stating that the denominator cannot be zero:

Encountered ValueError division by zero
None
5.0

In the divide function definition, we use the try block to handle any possible ValueError caused by a zero division operation. Within the try block if the division operation is successful, then we return the quotient. But if there is a zero division operation, a ValueError is raised and we catch it inside the except block and print out an error message. We then add code to our except block to handle the error.

Conclusion

The ValueError is one of the most common exceptions in Python. It occurs when a function or operation receives the right type of argument(s) but with inappropriate values. Causes of ValueError can be related to calling the wrong function with incorrect arguments, parsing a string, or performing string manipulation. The best way to deal with the ValueError is to understand the cause of the error, and implement methods to handle it such as using try…except block, input validation, or pre-processing the input data to make it appropriate for the function.

Leave a Reply

Your email address will not be published. Required fields are marked *