The Python ValueError
is an exception that occurs when a function receives an argument of the correct data type but an inappropriate value. This error usually occurs in mathematical operations that require a certain kind of value.
To use an analogy, imagine trying to enroll an adult in a children's school. The person is a valid human, but their age is inappropriate for the setting. Similarly, a ValueError
occurs when a function receives the correct type of input but with an unsuitable value.
What Causes ValueError
The Python ValueError
is raised when an object is assigned the right data type but the wrong value for a certain operation. Some of the most common scenarios where this can happen are:
- If the value is invalid for the operation. For example, if a negative integer is passed to a square root operation.
- Performing an operation when the value does not exist. For example, trying to remove a value from a list where it does not exist.
- Trying to unpack more values than available. For example, trying to unpack values from a list with 5 items to 3 variables.
ValueError Examples
Example One
Here’s an example of a Python ValueError
raised when trying to perform a square root operation on a negative number:
import math
math.sqrt(-100) #Performing square root operation on negative number
In the above example, a negative integer is passed to the math.sqrt()
function. Since the function expects a positive integer, running the above code raises a ValueError
:
Traceback (most recent call last):
File "test.py", line 3, in <module>
math.sqrt(-100)
ValueError: math domain error
Example Two
Here’s an example of a Python ValueError
raised when trying to remove a value from a list where it does not exist:
myString = "Hello"
myList = ["World"]
myList.remove(myString) #Trying to remove value from list that does not contain it
In the above example, the variable myString
with a value of "Hello"
is attempted to be removed from the list myList
. Since myList
does not contain the value, running the above code raises a ValueError
:
Traceback (most recent call last):
File "test.py", line 3, in <module>
myList.remove(myString) #Trying to remove value from list that does not contain it
ValueError: list.remove(x): x not in list
Example Three
Here’s an example of a Python ValueError
raised when trying to unpack more values from a list than available:
myList = [10, 9, 8, 7, 6, 5]
i,j,k = myList #Trying to unpack more values than available variables
In the above example, the list myList
containing 5 values is attempted to be unpacked and assigned to 3 variables. Since the number of values exceed the number of available variables, running the above code raises a ValueError
:
Traceback (most recent call last):
File "test.py", line 2, in <module>
i,j,k = myList
ValueError: too many values to unpack (expected 3)
How to Fix ValueError Exceptions
To resolve the ValueError
in Python code, a try-except block can be used. The lines of code that can throw the ValueError
should be placed in the try
block, and the except
block can catch and handle the error.
Using this approach, the previous examples can be updated to handle the error:
Example One
Code:
import math
try: #Placing operation in try-except block
math.sqrt(-100)
except ValueError:
print('Positive number expected for square root operation')
Here, a check is performed for the ValueError
using the try-except block. When the above code is executed, the except
block catches the ValueError
and handles it, producing the following output:
Positive number expected for square root operation
Example Two
Code:
myString = "Hello"
myList = ["World"]
try: #Placing operation in try-except block
myList.remove(myString)
except ValueError:
print('List does not contain value')
Output:
List does not contain value
Example Three
Code:
myList = [10, 9, 8, 7, 6, 5]
try: #Placing operation in try-except block
i,j,k = myList
except ValueError:
print('Too many values to unpack')
Output:
Too many values to unpack
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!