Python第二讲基本数据类型

Python第二讲基本数据类型

python的数据类型大致有这几类:

  • 数字Number
python3支持4种:int,float,bool,complex(复数),可以用type()来查看类型
>>>a,b,c,d=1,1.2,True,1+1.3j
>>>print(type(a),type(b),type(c),type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
运算也很简单,可以直接计算
>>>1+1 #加法
2
>>>9.9-1.8 #减法
8.1
>>>3*0.9 #乘法
2.7
>>>8/2 #除法:得到一个浮点数
4.0
>>>8/1.1 #除法:得到一个浮点数
7.2727272727272725
>>>8//3 #除法:得到一个整数
2
>>>13%5 #取余
2
>>>5**3 ##5的3次方
125

  • 字符串String
Python中的字符串str用单引号(’ ‘)或双引号(” “)括起来,当然也可以用三个单引号三个双引号,同时使用反斜杠()转义特殊字符
>>>a,b,c,d='hello',"world",'''hello''',"""python"""
>>>print(a,type(a),b,type(b),c,type(c),d,type(d))
hello <class 'str'> world <class 'str'> hello <class 'str'> python <class 'str'>
>>>c='I\'m Tom'
>>>print(c,type(c))
I'm Tom <class 'str'>
\n是换行,有的时候不想转义,那么可在字符串前面加r
>>>c='C:\Program Files\nature'
>>>print(c,type(c))
C:\Program Files
ature <class 'str'>
>>>c=r'C:\Program Files\nature'
>>>print(c,type(c))
C:\Program Files\nature <class 'str'>
字符串拼接用+,重复出现用*,长度用len()
>>>c='hello'
>>>print('Str'+'ing','ok'*3,len(c))
String okokok 5
字符串的索引规则从左为0开始,从右为-1开始
>>>c='hello'
>>>print(c[0],c[4]) #注意不能越界
h  o
>>>print(c[-1],c[-5])
o  h
  • 列表list
和java的数组差不多,不过里面的元素类型可以不相同
>>>a=['My','age',25]
>>>print(a,type(a))
['My', 'age', 25] <class 'list'>
list可以直接用+拼接,并且可以通过下标获取值
>>>a=['My','age',24]
>>>a+['hello','python']
['My', 'age', 25, 'hello', 'python']
>>>a[0]
'My'
  • 元组Tuple
tuple和list差不多,tuple是写在小括号中,用逗号隔开
>>>a=(1,2,3,4,'hello')
>>>print(a,type(a))
(1, 2, 3, 4, 'hello') <class 'tuple'>
和list用法差不多,就不详细介绍了,说几个注意点:
1.支持+号拼接
2.元素值不可改变
3.可以把list放元组中
4.支持空元组
5.支持索引,索引用方括号,例如:a[0]
  • 集合Sets
set是无序不重复的集合,可以用()也可以用{},用()时必须写上set()
>>>a={'a','b','c','a'}
>>>print(a,type(a))
{'b', 'c', 'a'} <class 'set'>
>>>b=set('aabbcc')
>>>print(b,type(b))
{'b', 'c', 'a'} <class 'set'>
>>>c=('ddffcc')
>>>print(c,type(c))
ddffcc <class 'str'>
  • 字典Dictionaries
和java中的json很像,是无序的键值对,关键字不能重复
>>>computer={u'联想':u'中国',u'华硕':u'台湾'}
>>>print(computer,type(computer))
{'联想': '中国', '华硕': '台湾'} <class 'dict'>
>>>computer[u'联想']
'中国'
>>>computer[u'三星']=[u'韩国']
>>>print(computer,type(computer))
{'联想': '中国', '三星': ['韩国'], '华硕': '台湾'} <class 'dict'>
>>>del computer[u'三星']
>>>print(computer,type(computer))
{'联想': '中国', '华硕': '台湾'} <class 'dict'>
>>>u'联想' in computer
True
>>>u'三星' in computer
False

目录

[TOC]来生成目录:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值