python——type()函数和isintance()函数

转载自:https://blog.csdn.net/VonSdite/article/details/76860407

引言

  • 有时候可能需要确定一个变量的数据类型, 例如用户的输入, 当需要用户输入一个整数,
    但用户却输入一个字符串,就有可能引发一些意想不到的错误或者导致程序崩溃.
  • 简言之, 就是程序设计过程中, 有时是需要确定变量的数据类型的, 不然可能会导致错误

获取数据类型

python 可以通过type()函数来获取变量的数据类型

如:

>>> type(666) # 整数类型
<class 'int'>

>>> type('666') # 字符串类型
<class 'str'>

>>> type(66.666) # 浮点数类型
<class 'float'>

>>> type(True) # 布尔类型
<class 'bool'>

>>> type([66,66,66,666]) # 列表类型
<class 'list'>

>>> type((66,66,666,666)) # 元组类型
<class 'tuple'>

>>> type(range(5)) # range类型
<class 'range'>

判断变量数据类型是否相等

  • 方法一, 使用isinstance()函数 (推荐)

isintance()函数有两个参数, 第一个参数是待确定类型的数据, 第二个参数是指定一个数据类型, 若第一个参数的数据类型同第二个参数指定的数据类型, 返回 True, 否则返回False

>>> print(isinstance(6666, int))
True
>>> print(isinstance(6666, float))
False
>>> print(isinstance(6666., float))
True
>>> print(isinstance('6666', str))
True

  • 方法二, 使用type()函数
>>> a = 6666
>>> b = '6666'
>>> if type(a) == type(b):
... 	print('Type of a and type of b is the same')
... else:
... 	print('Not the same')
... 
Not the same
>>> 

发布了23 篇原创文章 · 获赞 5 · 访问量 5361

猜你喜欢

转载自blog.csdn.net/ytraister/article/details/100067204