Skip to main content

How to Validate Numeric Ranges in Python

Validating that a number falls within a specific range is a fundamental requirement for data integrity. Whether you are checking user age, temperature thresholds, or financial limits, ensuring values are within bounds prevents logical errors and security vulnerabilities.

This guide explores multiple ways to validate numeric ranges in Python, from simple comparison operators to reusable decorators and custom classes.

Method 1: Using Comparison Operators (Standard)

The most Pythonic way to check if a value falls between two bounds is using chained comparison operators. This works for both integers and floats.

Syntax: min_val <= value <= max_val

def validate_age(age):
# ✅ Correct: Chained comparison
if 18 <= age <= 65:
return True
return False

print(f"Age 25 valid? {validate_age(25)}")
print(f"Age 10 valid? {validate_age(10)}")

Output:

Age 25 valid? True
Age 10 valid? False
note

This is cleaner and more readable than the verbose age >= 18 and age <= 65.

Method 2: Using range() for Integers

If you are dealing strictly with integers, you can use the in range() syntax.

Syntax: value in range(start, stop)

score = 85

# ✅ Correct: Check if score is between 0 and 100 (inclusive)
# Note: range() stop value is exclusive, so use 101 to include 100
if score in range(0, 101):
print("Valid score.")
else:
print("Invalid score.")

Output:

Valid score.
warning

range() only works with integers. Using floats (e.g., 85.5 in range(...)) will raise a TypeError or return incorrect results depending on context.

Method 3: Using Decorators for Reusable Validation

If you have many functions that require inputs to be within specific bounds, a decorator allows you to define the rule once and apply it everywhere.

def validate_range(min_val, max_val):
def decorator(func):
def wrapper(value):
if not (min_val <= value <= max_val):
raise ValueError(f"Value {value} must be between {min_val} and {max_val}")
return func(value)
return wrapper
return decorator

@validate_range(0, 100)
def process_percentage(value):
print(f"Processing {value}%...")

try:
process_percentage(150)
except ValueError as e:
print(f"Error: {e}")

Output:

Error: Value 150 must be between 0 and 100

Method 4: Custom Validator Class

For complex applications, a validator class offers flexibility, allowing optional bounds (e.g., only a minimum) and reusable instances.

class RangeValidator:
def __init__(self, min_val=None, max_val=None):
self.min_val = min_val
self.max_val = max_val

def validate(self, value):
if self.min_val is not None and value < self.min_val:
return False
if self.max_val is not None and value > self.max_val:
return False
return True

# Validator for positive prices
price_validator = RangeValidator(min_val=0.01)

print(f"Price 10.50 valid? {price_validator.validate(10.50)}")
print(f"Price -5.00 valid? {price_validator.validate(-5.00)}")

Output:

Price 10.50 valid? True
Price -5.00 valid? False

Conclusion

To validate numeric ranges in Python:

  1. Use Chained Comparison (min <= x <= max) for the most readable, standard solution.
  2. Use range() only for integer checks where the exclusive upper bound logic is clear.
  3. Use Decorators to enforce constraints on function arguments automatically.