Value Error

ValueErrors in Python

In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

This is not to be confused with types in Python. For instance, imagine you have a dog and you try to put it in a fish tank. This would be an example of a type error, because animals of type ‘dog’ certainly are not the same as animals of type ‘fish’.

On the other hand, imagine we tried to put a Great Dane into a Chihuahua’s kennel. This would be a problem with the value of the dog, because although they are both of type ‘dog’, a Chihuahua’s kennel would not be able to accept a dog the size of a Great Dane.

To see this more clearly in Python, note the following examples:

>>> int(5.6754)
Fig. 1: A valid int conversion

Since the float 5.6754 is numeric data, Python can convert it to an integer. The following, however, won't work so well:

>>> int("dog")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'dog'
Fig. 2: A decidedly invalid int conversion

In PyLearn, we would see the following message:

>>> int("dog")
ValueError: int() cannot convert 'dog' into an integer.
Fig. 3: The same message, PyLearn-style

Any time you wish to convert the type of an object, you need to make sure that the value associated with that object is a valid value.

Other ValueErrors in Python

You can also trigger a ValueError in Python when you try to perform an operation on a value that doesn’t exist. For instance, imagine the following example:

>>> myVar = 5
>>> list = []
>>> list.remove(myVar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

In this example, we define a variable ‘myVar’ to have the value 5. We then try to remove this value from a list that doesn’t contain that value. Because 5 is not in the list, we cannot remove it, and Python returns a value error.

Additionally, you can also raise a ValueError in Python if you try to ‘unpack’ more values than you have. For instance:

>>> a, b, c, d = [3, 4, 5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack

This returns a value error, because there are too few values on the right-hand side for Python to ‘unpack.’ When Python tries to assign ‘d’ to a value on the right-hand side, it is unable to find any matching value to ‘unpack’, and thus throws a ValueError.