A ValueError
exception is raised when an inappropriate value but which is of correct type is used in an operation.
For example, consider what happens when we try to find the square root of a negative real number. The number is surely an integer but its square root is undefined , in such a case, Python raises a ValueError
.
The most common cause of ValueErr
or exception is when we pass an inappropriate value to a function, but which is of supported type.
In the above example, a ValueError is raised because while the builtin int()
functions takes string arguments, string "a"
cannot be converted to an integer representation.
ValueError and Unpacking
Retrieving elements from an iterable and assigning them to variables is referred to as "Unpacking". In such a case, a ValueError
is raised if the number of variables do not match the number of items in the argument. This is because in such cases, Python can't tell which value to assign to which variable.
What is the difference between ValueError and TypeError?
ValueError
and TypeError
exceptions are closely linked in that they both indicate when an incorrect data type has been used. ValueError occurs when an operation or a function receives an argument of the correct type, but an inappropriate value; TypeError occurs when an operation or function is applied to an object of an incorrect type.
Handling ValueError exceptions
To handle the ValueError
exception, you can use try and except blocks to catch the error and proceed accordingly.
#Define function "interactive_add" that returns sum of two integers entered by user
def interactive_add():
try:
x = int(input("Enter an integer:"))
y = int(input("Enter an integer:"))
print("{} + {} = {}".format(x, y, x + y))
except ValueError:
print("You did not enter an integer!")
#Call the function
interactive_add()
//Enter an integer: 7
//Enter an integer: "Hello!"
//You did not enter an integer!