在Python中检查变量是否为整数的方法

128 阅读1分钟

在本教程中,我们将在实例的帮助下学习如何在Python中检查变量是否为整数。

考虑一下,我们的代码中有以下变量。

age = 24

现在,我们需要检查上述变量是否是一个int。

使用type()函数

为了检查一个变量是否为整数,我们可以使用Python中内置的type() 函数。

type() 函数将变量作为一个参数,并返回以下对象的类型。

下面是一个例子。

age = 24

if type(name) == int:
    print('Variable is a integer')
else:
    print('Variable is not a integer')

输出。

'Variable is a integer'

在上面的代码中。

  1. 我们首先用一个整数初始化了这个变量。

  2. 然后我们用平等== 操作符来检查这两个值是否指的是同一个对象。

如果返回True ,则打印出variable is a integer ,如果变量不是整数,则返回False ,并打印出Variable is not a integer

另一个例子。

age = "23"

if type(age) == int:
    print('Variable is integer')
else:
    print('Variable is not a integer')

输出。

'Variable is not a integer'

我们也可以使用is ,而不是平等运算符,像这样。

age = 24

if type(age) is str:
    print('Variable is a integer')
else:
    print('Variable is not a integer')

使用isinstance()函数

另外,我们也可以使用Python中的isinstance() 函数来检查一个给定的变量是否是整数。

isinstance() 函数接收两个参数,第一个参数是object ,第二个参数是type ,然后如果一个给定的对象是指定的类型,它返回True ,否则它返回 False 。

age = 24

if  isinstance(name, int):
    print('Variable is a integer')
else:
    print('Variable is not a integer')