Skip to content

How to Validate Numeric Conditions in Python

How to validate numeric values in Python using isinstance(), safely convert numeric strings, check ranges with chained comparisons, and handle floating-point precision with math.isclose().

Validating numbers is a fundamental task in Python, from checking user inputs and form data to ensuring variables stay within safe bounds for mathematical operations.

This guide covers how to check if a value is a valid number (integer or float), how to compare values using standard operators, and how to use built-in functions like all() and math.isclose() for advanced validation.

Method 1: Checking Data Types (isinstance)

Before performing math operations, you must ensure the variable holds a numeric type (int or float). Using isinstance() is safer than type() because it supports subclasses.

def validate_numeric(value):
    if isinstance(value, (int, float)):
        print(f"'{value}' is a valid number.")
        return True
    else:
        print(f"'{value}' is NOT a number. It is {type(value).__name__}.")
        return False

validate_numeric(100)
validate_numeric(3.14)
validate_numeric("100") # String input

Output:

'100' is a valid number.
'3.14' is a valid number.
'100' is NOT a number. It is str.

Method 2: Validating Input Strings

User input (input()) always returns a string. To validate if this string represents a valid number, you can use .isdigit() for integers or a try-except block for broader numeric support (including floats and negative numbers).

Basic Integer Check

user_input = "123"

if user_input.isdigit():
    print("Valid positive integer.")
else:
    print("Invalid integer.")

Output:

Valid positive integer.

To handle floats and negative numbers, attempt to cast the value.

def is_valid_number_string(s):
    try:
        float(s) # Tries to convert to float
        return True
    except ValueError:
        return False

print(f"Is '-5.5' valid? {is_valid_number_string('-5.5')}")
print(f"Is 'abc' valid? {is_valid_number_string('abc')}")

Output:

Is '-5.5' valid? True
Is 'abc' valid? False

Method 3: Comparing Ranges and Values

Python supports chained comparison operators, which makes range validation concise and readable.

Range Validation

age = 25

if 18 <= age <= 65:
    print("Age is within the valid range.")
else:
    print("Age is out of bounds.")

Output:

Age is within the valid range.

Validating Multiple Conditions

Use all() to check a list of conditions at once.

x = 10
conditions = [
    isinstance(x, int),
    x > 0,
    x % 2 == 0
]

if all(conditions):
    print("x is a positive even integer.")

Output:

x is a positive even integer.

Method 4: Validating Float Equality (Precision)

Floating-point arithmetic is not perfectly precise. Direct comparison using == often fails (e.g., 0.1 + 0.2 == 0.3 is False). Use math.isclose() for reliable validation.

import math

val = 0.1 + 0.2
target = 0.3

print(f"Direct check: {val == target}")

print(f"Math check:   {math.isclose(val, target)}")

Output:

Direct check: False
Math check:   True

Conclusion

To validate numeric conditions effectively:

  1. Use isinstance(x, (int, float)) to ensure variables are numeric types.
  2. Use try-except float(s) to validate strings representing numbers.
  3. Use chained comparison (min <= x <= max) for range checks.
  4. Use math.isclose() when comparing floating-point results.
Navigation