7、赋值
Python不支持C语言中的自增1和自减1运算符,这是因为+和-也是单目运算符,Python会将--n解释为-(-n)从而得到n,同样++n的结果也是n。
8、数字
Python支持物种基本数字类型,其中有三种是整数类型。
- int(有符号整数)--从Python2.3开始,再也不会报整型溢出错误,结果会自动被转换为长整数。
- long(长整数)--表达范围远远超过C语言的长整数,进受限于用户计算机的虚拟内存总数。
- bool(布尔值)--特殊的整数,尽管布尔值由常量True和False来表示,如果将布尔值放到一个数字上下文环境中(比如将True与一个数字相加),True会被当成整数值1,而False则会被当成整数值0。
- float(浮点值)
- complex(复数)
9、字符串--定义为引号之间的字符集合。
Python支持使用成对的单引号或双引号,三引号。使用索引运算符([ ])和切片运算符([ : ])可以得到子字符串。字符串有其特有的索引规则:第一个字符的索引是0,最后一个字符的索引是-1。
加号(+)用于字符串连接运算,星号(*)则用于字符串重复。
>>> pystr = 'Python'
>>> iscool = 'is cool!'
>>> pystr[0]
'P'
>>> pystr[2:5]
'tho'
>>> iscool[:2]
'is'
>>> iscool[3:]
'cool!'
>>> iscool[-1]
'!'
>>> pystr + iscool
'Pythonis cool!'
>>> pystr + ' ' + iscool
'Python is cool!'
>>> pystr * 2
'PythonPython'
>>> '-' * 20
'--------------------'
>>> pystr = '''python
is cool'''
>>> pystr
'python\nis cool'
>>> print pystr
python
is cool
>>>
10、列表(List)和元组(Tuple)
可以保存任意数量任意类型的Python对象,可以存储不同类型的对象,通过从0开始的数字索引访问元素。
(1)不同点:
- 列表元素用中括号([ ])包裹,元素的个数及元素的值可以改变。
- 元组元素用小括号(())包裹,不可以更改(尽管他们的内容可以),元组可以看成是制度的列表。
(2)相同点:都可以通过切片运算([ ]和[ : ])得到子集,与字符串使用方法一样。
>>> aList = [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aList
[1, 5, 3, 4]
>>>
元组也可以进行切片运算,得到的结果也是元组(不能被修改):
>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>> aTuple[1]
77
>>> aTuple[1] = 5
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
aTuple[1] = 5
TypeError: 'tuple' object does not support item assignment
>>>
11、字典
Python中的映射数据类型,由键值对(key-value)构成。几乎所有类型的Python对象都可以用作键,不过一般还是以数字或字符串最为常用。值可以是任意类型的Python对象,字典元素用大括号({ })包裹。
>>> aDict = {'host': 'earth'}
>>> aDict['port'] = 80
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'
>>> for key in aDict:
print key, aDict[key]
host earth
port 80
>>>