How To Check If Something Is An Integer Python

7 min read

Checking if a value is an integer in Python is a fundamental task that appears in data validation, user input processing, and algorithm logic. On the flip side, while the concept seems straightforward, Python’s dynamic typing system and the distinction between types and values introduce nuances that every developer must understand to avoid subtle bugs. This guide explores the most reliable methods for integer verification, covering built-in functions, type checking, value validation, and edge cases involving floats, strings, and third-party libraries like NumPy Worth knowing..

Understanding the Difference: Type vs. Value

Before diving into the code, it is critical to distinguish between checking the type of an object and checking its value.

  • Type Checking: Asks, "Is this object an instance of the int class?" A variable holding 5.0 (a float) fails this check, even though mathematically it represents an integer.
  • Value Checking: Asks, "Does this value represent a whole number?" Both 5 (int) and 5.0 (float) pass this check.

Choosing the wrong approach is a common source of logic errors. To give you an idea, JSON data often returns numbers as floats, so a strict type check on an ID field might reject valid data.

Method 1: The isinstance() Function (Recommended for Type Checking)

The most Pythonic and dependable way to verify if an object is strictly an integer type is the built-in isinstance() function. It supports inheritance, meaning it returns True for subclasses of int (though custom int subclasses are rare in standard applications) The details matter here..

value = 42
print(isinstance(value, int))  # True

value = 42.0
print(isinstance(value, int))  # False

value = "42"
print(isinstance(value, int))  # False

Why prefer isinstance() over type()? Using type(value) is int is considered brittle because it returns False for any subclass of int. Since Python’s bool class is a subclass of int (True == 1, False == 0), isinstance(True, int) returns True. If you explicitly want to exclude booleans, you must add a specific check:

def is_strict_int(value):
    return isinstance(value, int) and not isinstance(value, bool)

print(is_strict_int(10))    # True
print(is_strict_int(True))  # False

Method 2: Checking if a Float Represents an Integer (float.is_integer())

When dealing with numerical computations, division, or data parsed from formats like JSON or CSV, you often encounter floats that are mathematically whole numbers (e.g., 10.0, -3.That's why 0). The float type provides a dedicated method for this: is_integer().

pi = 3.14159
whole = 10.0
negative = -5.0

print(pi.is_integer())      # False
print(whole.is_integer())   # True
print(negative.is_integer())# True

This method only exists on float objects. Calling it on an int or str raises an AttributeError. A safe wrapper function looks like this:

def is_whole_number(value):
    if isinstance(value, int):
        return True
    if isinstance(value, float):
        return value.is_integer()
    return False

print(is_whole_number(5))     # True
print(is_whole_number(5.0))   # True
print(is_whole_number(5.5))   # False
print(is_whole_number("5"))   # False

Method 3: Validating String Inputs

User input, configuration files, and network requests deliver data as strings. Plus, checking if a string represents an integer requires parsing logic. There are two main schools of thought here: Look Before You Leap (LBYL) using regex or string methods, and Easier to Ask for Forgiveness than Permission (EAFP) using try/except.

The EAFP Approach (Pythonic Standard)

Python culture favors trying the conversion and handling the exception if it fails. This handles signs (+, -), whitespace, and leading zeros automatically.

def is_int_string_eafp(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

print(is_int_string_eafp("42"))      # True
print(is_int_string_eafp("-10"))     # True
print(is_int_string_eafp("  7  "))   # True (whitespace handled)
print(is_int_string_eafp("3.14"))    # False
print(is_int_string_eafp("abc"))     # False

The LBYL Approach (Regex/String Methods)

If you need to validate without the overhead of exception handling (relevant in extremely tight loops) or need strict format control (e.g., rejecting leading zeros or whitespace), use Regular Expressions or str.isdigit() (with caveats).

Using str.isdigit(): This returns True only for positive integers without signs or spaces. It fails on negative numbers.

"42".isdigit()    # True
"-42".isdigit()   # False
" 42".isdigit()   # False

Using Regular Expressions (Strict Validation): Regex allows precise definition of "integer format."

import re

# Matches optional sign followed by digits, no leading zeros unless the number is 0
INTEGER_REGEX = re.compile(r'^[+-]?(?:0|[1-9]\d*)
Right Off the Press

Out Now

Explore a Little Wider

Parallel Reading

Thank you for reading about How To Check If Something Is An Integer Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home