在本教程中,我们将通过实例来学习如何在Python中检查一个变量是否是元组。
考虑一下,我们的代码中有以下变量。
nums = (4, 5, 6)
现在,我们需要检查上述变量是否是一个元组。
使用type()函数
为了检查一个变量是否是一个元组,我们可以使用Python中内置的type() 函数。
type() 函数将变量作为一个参数,并返回下面对象的类型。
下面是一个例子。
nums = (4, 5, 6)
if type(nums) == tuple:
print('Variable is tuple')
else:
print('Variable is not a tuple')
输出。
'Variable is tuple'
在上面的代码中。
-
我们首先用一个元组初始化了这个变量。
-
然后我们使用
==操作符来检查这两个值是否指的是同一个对象。
如果它返回True ,那么它就打印出variable is tuple ,如果变量不是一个元组,那么它就返回False ,并打印出Variable is not a tuple 。
另一个例子。
nums = [4, 5, 6]
if type(nums) == tuple:
print('Variable is tuple')
else:
print('Variable is not a tuple')
输出。
'Variable is not a tuple'
使用isinstance()函数
同样地,我们也可以使用Python中的isinstance() 函数来检查一个给定的变量是否是元组。
isinstance() 函数接收两个参数,第一个参数是object ,第二个参数是type ,然后如果给定的对象是指定的类型,它返回True ,否则它返回 False 。
nums = (4, 5, 6)
if isinstance(nums, tuple):
print('Variable is tuple')
else:
print('Variable is not a tuple')