01 Python数据类型-类型转换

1. 什么是数据类型

  • 程序对处理的数据进行分类

2. 为什么区分

  • 根据不同的数据类型分配不同的空间
  • 根据不同的数据类型,进行不同的数据处理

In [2]:

print(6+6)      #数值类型
print('6'+'6')  #字符串拼加
12
66

3. 数据类型

3.1 常用数据类型
  1. numbers(数值类型)
    • int
    • long
    • float
    • complex
  2. bool(布尔类型)
    • True
    • False
  3. string(字符串)
    • ‘abc’
    • ‘‘abc’’
3.2 查看数据类型

In [4]:

print(type(6))
print(type('6'))
<class 'int'>
<class 'str'>

4 数据类型转换

In [5]:

#不支持不同数据类型进行+运算 因为Python是 **强类型**
num = '6'
print(num+6)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-02503ca2c7e3> in <module>
      1 num = '6'
----> 2 print(num+6)

TypeError: can only concatenate str (not "int") to str

In [8]:

print(int(num)+6)
print(type(int(num)))
print(str(6)+num)
12
<class 'int'>
66

In [9]:

score = input('请输入一个数字')   #等待用户的指令并获取,再执行下一条指令
print(score + 6)
#键盘获取的是str型,需要转换为int
请输入一个数字6
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-580f8a224e0e> in <module>
      1 score = input('请输入一个数字')   #等待用户的指令并获取,再执行下一条指令
----> 2 print(score + 6)

TypeError: can only concatenate str (not "int") to str

In [11]:

score = input('请输入一个数字')   #等待用户的指令并获取,再执行下一条指令
print(type(score))
print(int(score)+6)
请输入一个数字6
<class 'str'>
12

5 面试补充

5.1 动态类型和静态类型
  • 静态类型:类型是编译的时候确定的,后期无法修改
  • 动态类型:类型是运行的时候判定的,可以动态修改
5.2 强类型和弱类型
  • 强类型:类型比较强势, 不轻易随着环境的变化而变化
  • 弱类型:类型比较柔弱, 不同的环境下, 很容易被改变
5.3 结论
  • Python是强类型动态类型的语言
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值