欢迎访问宙启技术站
智能推送

如何使用Python的numbers.Integral()方法判断一个变量是否为整数类型

发布时间:2024-01-03 05:02:09

Python的numbers.Integral()方法判断一个变量是否为整数类型。其参数为待判断的变量,如果变量是整数类型,返回True;否则返回False。

下面是一个例子:

from numbers import Integral

def check_if_integer(var):
    if isinstance(var, Integral):
        print(f"{var} is an integer.")
    else:
        print(f"{var} is not an integer.")

# 使用例子
check_if_integer(5)            # 输出:5 is an integer.
check_if_integer(5.0)          # 输出:5.0 is not an integer.
check_if_integer("hello")      # 输出:hello is not an integer.
check_if_integer([1, 2, 3])    # 输出:[1, 2, 3] is not an integer.

在上述例子中,我们定义了一个名为check_if_integer的函数,该函数使用numbers.Integral()方法判断输入的变量是否为整数类型,并输出相应的结果。我们对不同类型的变量进行了判断:整数、浮点数、字符串和列表。从输出结果可以看出,只有整数类型的变量被判断为整数。

这里需要注意的是,numbers.Integral()方法会判断Python内置的整数类型,如int和bool,以及其他继承自numbers.Integral基类的自定义整数类型。