A ValueError occurs when a function receives an argument of the correct data type but with an invalid value. In other words, Python understands the type of the value provided, but the value itself is not suitable for the operation being performed.
num = "Python"
print(float(num))
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: could not convert string to float: 'Python'
Explanation: float() function can convert numeric values into floating-point numbers. Since "Python" is not a valid numeric value, Python raises a ValueError.
Common Causes
1. Using Invalid Values with the Math Module: Some mathematical functions only accept specific values. Providing invalid values can result in a ValueError.
import math
print(math.factorial(-5))
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: factorial() not defined for negative values
Explanation: factorial of a negative number is not defined. Therefore, math.factorial() raises a ValueError when a negative value is passed.
2. Incorrect Unpacking of Values: ValueError can occur when the number of variables does not match the number of values being unpacked.
items = ["Python", "Java", "C++"]
a, b, c, d = items
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: not enough values to unpack (expected 4, got 3)
Explanation: list contains only three elements, but four variables are used during unpacking. Since Python cannot assign four variables from three values, a ValueError is raised.
Handling ValueError
1. try-except: A try-except block allows us to handle ValueError gracefully and prevent the program from terminating unexpectedly.
num = "Python"
try:
print(float(num))
except ValueError:
print("Invalid numeric value.")
Output
Invalid numeric value.
Explanation: conversion raises a ValueError, which is caught by the except block. Instead of crashing, the program displays a meaningful error message.
2. Validating Input Before Processing: Checking values before performing operations can help avoid ValueError.
import math
num = 5
if num >= 0:
print(math.factorial(num))
else:
print("Factorial is only defined for non-negative numbers.")
Output
120
Explanation: Before calling math.factorial(), the program checks whether the value is non-negative. This prevents a ValueError from occurring.
3. Correct Number of Variables During Unpacking: Always ensure that the number of variables matches the number of values being unpacked.
items = ["Python", "Java", "C++"]
a, b, c = items
print(a)
print(b)
print(c)
Output
Python Java C++
Explanation: list contains three values and three variables are used for unpacking, so the operation executes successfully without any errors.