You’re running your Python code, and suddenly you see a big red error message: ValueError. Don’t worry — this is one of the most common errors in Python, and it’s totally fixable.
A ValueError happens when Python receives a value that has the right type but is inappropriate for the operation. For example, trying to convert the text "hello" into a number.
In this article, we’ll walk through why this error happens and how to fix it step by step.
目次
What Causes a ValueError in Python
- Converting a non-numeric string to a number — For example,
int("abc")will raise a ValueError because"abc"is not a valid number. - Unpacking the wrong number of values — For example, trying to assign three variables from a list that only has two items.
- Passing an out-of-range value to a function — Some functions only accept values within a certain range, and passing something outside that range triggers this error.
Fix 1: Handle String-to-Number Conversion
This is the most common cause of ValueError. When you use int() or float() on user input or data that isn’t a clean number, Python raises this error.
Example of the error:
# This will raise ValueError: invalid literal for int()
user_input = "hello"
number = int(user_input)
Step 1: Check what value is causing the error. Add a print statement before the conversion.
# Print the value to see what's being converted
print(f"Trying to convert: '{user_input}'")
number = int(user_input)
Step 2: Use try-except (a way to catch errors before they crash your program) to handle the error gracefully.
user_input = input("Enter a number: ")
try:
number = int(user_input)
print(f"Your number is {number}")
except ValueError:
print("That's not a valid number. Please enter digits only.")
If the program prints your number without an error, you’re all set.
Step 3: If you want to keep asking until you get a valid number, use a loop.
while True:
user_input = input("Enter a number: ")
try:
number = int(user_input)
break # Exit the loop if conversion succeeds
except ValueError:
print("That's not a valid number. Try again.")
print(f"You entered: {number}")
If the program accepts valid numbers and rejects invalid ones, you’re good to go.
Fix 2: Correct Value Unpacking
If your ValueError mentions something about “not enough values to unpack” or “too many values to unpack,” the problem is with how you’re assigning variables from a list or tuple (an ordered collection of items).
Example of the error:
# This will raise ValueError: not enough values to unpack
a, b, c = [1, 2] # 3 variables but only 2 values
Step 1: Check the length of the data before unpacking.
data = [1, 2]
print(f"Number of items: {len(data)}") # Shows 2
Step 2: Make sure the number of variables matches the number of values.
# Match the number of variables to the data
a, b = [1, 2] # 2 variables for 2 values — works correctly
print(a, b)
If the values print correctly without errors, you’ve fixed it.
Step 3: If the data length varies, use the * operator to collect extra values.
# The * collects any remaining items into a list
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
Fix 3: Validate Values Before Passing to Functions
Some functions only accept specific values. For example, math.sqrt() raises a ValueError if you pass a negative number.
import math
# This raises ValueError: math domain error
result = math.sqrt(-1)
Step 1: Check the value before passing it to the function.
import math
number = -1
if number >= 0:
result = math.sqrt(number)
print(f"Square root: {result}")
else:
print("Cannot calculate square root of a negative number.")
If the program handles negative numbers gracefully, you’re done.
What to Do If It Still Doesn’t Work
If none of the fixes above solve your ValueError, try these steps:
- Read the full error message carefully — Python tells you exactly which line and what value caused the problem.
- Print the variable right before the line that causes the error to see what it actually contains.
- Check your data source — If the data comes from a file or API (a service your code talks to), the format might have changed.
- Search the exact error message on Stack Overflow — chances are someone has had the same problem.
Summary
- A ValueError in Python means the value is wrong for the operation, even if the type is correct.
- The most common fix is using
try-exceptto handle invalid conversions gracefully. - Always check and validate your data before passing it to functions.
Related articles:
- type-error-python.html
- name-error-not-defined.html
- syntax-error-invalid-syntax.html

















Leave a Reply