如何检查变量是否为整数?


当前回答

我可以检查数字是否是整数,包括像7.0这样的数字

def is_int(x):
    if x - round(x) == 0 :
        return True
    else:
        return False

其他回答

import numpy as np

if (np.floor(x)-x == 0):
  return "this is an int"

如果你想检查不考虑Python版本(2。x vs . 3.x),使用六(PyPI)和它的integer_types属性:

import six

if isinstance(obj, six.integer_types):
    print('obj is an integer!')

在六个(一个非常轻量级的单文件模块)中,它只是这样做的:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    integer_types = int,
else:
    integer_types = (int, long)

一个简单的方法是直接检查除以1的余数是否为0。

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'

最简单的方法是:

if n==int(n):
    --do something--    

变量n在哪

为什么不直接检查您想检查的值是否等于它本身转换为一个整数,如下所示?

def isInt(val):
    return val == int(val)