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
>>> 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值