杰瑞科技汇

Python中如何判断if一个数是整数?

Of course! In Python, there are several ways to check if a value is an integer. The best method to use depends on whether you're checking for the type of the object or its mathematical value.

Python中如何判断if一个数是整数?-图1
(图片来源网络,侵删)

Let's break down the most common and Pythonic ways to do this.


Summary: Which Method to Use?

Your Goal Best Method Example
Check for a whole number value, regardless of its type (e.g., 5, 0, numpy.int32(5)). isinstance(value, (int, float)) and value.is_integer() isinstance(5.0, (int, float)) and 5.0.is_integer()
Check for the specific int type, excluding floats or other integer-like types. type(value) is int or isinstance(value, int) type(5) is int
Check for a whole number value in a robust way (e.g., for user input from a string). isinstance(value, (int, float, str)) and float(value).is_integer() float("10").is_integer()

Method 1: Check for the Integer int Type

This is the most straightforward approach. You want to know if the variable's type is exactly int. This is useful when you need to perform operations specific to the int class.

Using type()

The type() function returns the class of an object. You can compare it directly to int.

x = 10
y = 10.0
z = "10"
w = True # In Python, bool is a subclass of int
print(f"type(x) is int: {type(x) is int}")      # True
print(f"type(y) is int: {type(y) is int}")      # False, it's a float
print(f"type(z) is int: {type(z) is int}")      # False, it's a string
print(f"type(w) is int: {type(w) is int}")      # False, it's a bool

Using isinstance() (Recommended)

The isinstance() function is generally preferred over type(). It checks if an object is an instance of a class or of a subclass. This is more flexible and robust, especially with inheritance.

Python中如何判断if一个数是整数?-图2
(图片来源网络,侵删)
x = 10
y = 10.0
z = "10"
w = True # bool is a subclass of int
print(f"isinstance(x, int): {isinstance(x, int)}")   # True
print(f"isinstance(y, int): {isinstance(y, int)}")   # False
print(f"isinstance(z, int): {isinstance(z, int)}")   # False
print(f"isinstance(w, int): {isinstance(w, int)}")   # True! Because bool is a subclass of int.

Note: If you want to exclude booleans, you must add an extra check:

isinstance(x, int) and not isinstance(x, bool)

Method 2: Check for a Whole Number Value (The Pythonic Way)

Often, you don't care about the type of the number, only that it represents a whole number (an integer value). For example, 10 and 0 are both whole numbers. This is the most common real-world requirement.

The best way to do this is to check if the value is a number (int or float) and then use the .is_integer() method, which exists on float objects.

def is_whole_number(value):
    """Checks if a value has an integer value, regardless of its type."""
    # First, check if it's a number (int or float)
    if not isinstance(value, (int, float)):
        return False
    # If it's an int, it's automatically a whole number
    if isinstance(value, int):
        return True
    # If it's a float, check if it represents a whole number
    return value.is_integer()
# --- Examples ---
print(f"10: {is_whole_number(10)}")           # True
print(f"10.0: {is_whole_number(10.0)}")       # True
print(f"10.5: {is_whole_number(10.5)}")       # False
print(f"-5: {is_whole_number(-5)}")           # True
print(f"-7.0: {is_whole_number(-7.0)}")       # True
print(f"'10': {is_whole_number('10')}")       # False (it's a string)
print(f"None: {is_whole_number(None)}")       # False

Why this is robust:

Python中如何判断if一个数是整数?-图3
(图片来源网络,侵删)
  1. isinstance(value, (int, float)) correctly filters out non-numeric types like strings.
  2. isinstance(value, int) handles all actual int types quickly.
  3. value.is_integer() is the perfect tool for checking if a float represents a whole number.

Method 3: Handling Other Numeric Types (like NumPy)

If you work with libraries like NumPy, you might encounter numpy.int32 or numpy.int64. These are not instances of Python's built-in int.

import numpy as np
np_int = np.int32(42)
py_int = 42
print(f"isinstance(np_int, int): {isinstance(np_int, int)}") # False
print(f"type(np_int) is int: {type(np_int) is int}")         # False

To handle these, you can check against the "abstract base class" for integers from the numbers module. This is the most "correct" way from a type-checking perspective.

import numbers
import numpy as np
np_int = np.int32(42)
py_int = 42
a_float = 42.0
print(f"isinstance(np_int, numbers.Integral): {isinstance(np_int, numbers.Integral)}") # True
print(f"isinstance(py_int, numbers.Integral): {isinstance(py_int, numbers.Integral)}") # True
print(f"isinstance(a_float, numbers.Integral): {isinstance(a_float, numbers.Integral)}") # False

numbers.Integral is an abstract base class that int, numpy.int32, etc., are registered with. This is the best choice for library code that needs to be generic.


Method 4: Checking a String that Represents an Integer

A very common task is validating user input. You often get a string and need to check if it can be converted to an integer.

def is_integer_string(s):
    """Checks if a string can be converted to an integer."""
    if not isinstance(s, str):
        return False
    try:
        int(s)
        return True
    except ValueError:
        return False
# --- Examples ---
print(f"'123': {is_integer_string('123')}")       # True
print(f"'-456': {is_integer_string('-456')}")     # True
print(f"'0': {is_integer_string('0')}")           # True
print(f"'12.3': {is_integer_string('12.3')}")     # False
print(f"'hello': {is_integer_string('hello')}")   # False
print(f"123: {is_integer_string(123)}")           # False (it's not a string)

This try-except block is the standard and most reliable way to parse strings into numbers.

分享:
扫描分享到社交APP
上一篇
下一篇