Python ValueError Code Examples - Quick Fix Snippets
Ready-to-use Python code snippets to handle and prevent ValueError with practical examples for common scenarios.
Python ValueError Code Examples - Quick Fix Snippets
Collection of ready-to-use Python code snippets to handle and prevent ValueError in common scenarios. Use these examples to quickly implement robust error handling in your projects.
String to Number Conversion #
Safe Integer Conversion #
🐍 Try it yourself
Advanced Number Validator #
def parse_number(value, num_type=int):
"""Parse string to number with detailed error info"""
if not isinstance(value, str):
raise ValueError(f"Expected string, got {type(value).__name__}")
value = value.strip()
if not value:
raise ValueError("Cannot convert empty string")
try:
return num_type(value)
except ValueError as e:
raise ValueError(f"Invalid {num_type.__name__}: '{value}'") from e
# Example usage
try:
result = parse_number("12.5", float)
print(f"Success: {result}")
except ValueError as e:
print(f"Error: {e}")
List Operations Error Handling #
Safe List Index #
🐍 Try it yourself
Safe List Remove #
def safe_remove(lst, value):
"""Remove value from list if it exists, return success status"""
try:
lst.remove(value)
return True, f"Removed '{value}'"
except ValueError:
return False, f"'{value}' not found in list"
# Example
items = [1, 2, 3, 4]
success, message = safe_remove(items, 3)
print(f"Status: {success}, Message: {message}")
print(f"List: {items}")
Math Operations Error Handling #
Safe Math Functions #
🐍 Try it yourself
Input Validation Utilities #
Universal Input Validator #
class InputValidator:
"""Reusable input validation utilities"""
@staticmethod
def validate_positive_number(value, name="value"):
"""Ensure number is positive"""
if not isinstance(value, (int, float)):
try:
value = float(value)
except ValueError:
raise ValueError(f"{name} must be numeric")
if value <= 0:
raise ValueError(f"{name} must be positive, got {value}")
return value
@staticmethod
def validate_in_range(value, min_val, max_val, name="value"):
"""Ensure value is within specified range"""
if not (min_val <= value <= max_val):
raise ValueError(f"{name} must be between {min_val} and {max_val}")
return value
@staticmethod
def validate_choice(value, choices, name="value"):
"""Ensure value is one of allowed choices"""
if value not in choices:
raise ValueError(f"{name} must be one of {choices}")
return value
# Usage example
validator = InputValidator()
try:
age = validator.validate_positive_number("25", "age")
age = validator.validate_in_range(age, 0, 120, "age")
print(f"Valid age: {age}")
except ValueError as e:
print(f"Validation error: {e}")
Unpacking Error Prevention #
Safe Unpacking #
🐍 Try it yourself
Flexible Unpacking #
def flexible_unpack(data, min_count=1):
"""Unpack with minimum count requirement"""
if len(data) < min_count:
raise ValueError(f"Need at least {min_count} values, got {len(data)}")
# Return first values and remainder
if min_count == 1:
return data[0], data[1:]
else:
return data[:min_count], data[min_count:]
# Example
try:
first, rest = flexible_unpack([1, 2, 3, 4, 5])
print(f"First: {first}, Rest: {rest}")
except ValueError as e:
print(f"Error: {e}")
Custom ValueError Classes #
Specific Error Types #
class InvalidFormatError(ValueError):
"""Raised when data format is invalid"""
pass
class OutOfRangeError(ValueError):
"""Raised when value is outside valid range"""
pass
def validate_email(email):
"""Validate email format"""
if not isinstance(email, str):
raise InvalidFormatError("Email must be a string")
if "@" not in email or "." not in email:
raise InvalidFormatError("Invalid email format")
return email.lower()
def validate_percentage(value):
"""Validate percentage value"""
try:
value = float(value)
except ValueError:
raise InvalidFormatError("Percentage must be numeric")
if not (0 <= value <= 100):
raise OutOfRangeError("Percentage must be between 0 and 100")
return value
# Usage with specific error handling
try:
email = validate_email("[email protected]")
percentage = validate_percentage("95.5")
print(f"Valid: {email}, {percentage}%")
except InvalidFormatError as e:
print(f"Format error: {e}")
except OutOfRangeError as e:
print(f"Range error: {e}")
Error Context Manager #
ValueError Handler #
🐍 Try it yourself
Batch Validation #
Validate Multiple Values #
def validate_batch(values, validator_func, stop_on_first_error=True):
"""Validate multiple values with optional error collection"""
results = []
errors = []
for i, value in enumerate(values):
try:
result = validator_func(value)
results.append(result)
except ValueError as e:
error_msg = f"Index {i}: {e}"
errors.append(error_msg)
if stop_on_first_error:
raise ValueError(f"Validation failed at {error_msg}")
results.append(None)
return results, errors
# Example usage
def validate_positive_int(x):
x = int(x)
if x <= 0:
raise ValueError("Must be positive")
return x
test_values = ["10", "-5", "abc", "20"]
try:
results, errors = validate_batch(test_values, validate_positive_int, False)
print(f"Results: {results}")
print(f"Errors: {errors}")
except ValueError as e:
print(f"Batch validation failed: {e}")
Summary #
These code snippets provide robust ValueError handling for common Python scenarios:
- String conversion with safe fallbacks
- List operations with existence checks
- Math functions with domain validation
- Input validation with clear error messages
- Custom error types for specific scenarios
- Context managers for clean error handling
- Batch processing with error collection
Copy and adapt these snippets to handle ValueError effectively in your Python projects. Each example includes proper error checking and meaningful error messages to help with debugging.