Python语句与表达式
python的值类型:int,str,tuple — 元素不可变的,要改变只能重新声明或者覆盖
python的引用类型:set,list,dict — 元素的值时可变的
值类型不可变
>>> a = 1
>>> b = a
>>> print(a)
1
>>> print(b)
1
>>> a = 3
>>> print(a)
3
>>> print(b)
1
引用类型可以变
>>> a = [1,2,3]
>>> b = a
>>> print(a)
[1, 2, 3]
>>> print(b)
[1, 2, 3]
>>> print(a[0])
1
>>> a[0] = "1"
>>> print(a)
['1', 2, 3]
>>> print(b)
['1', 2, 3]
>>> a = "hello"
>>> id(a)
2552494650512
>>> a = a + "python"
>>> print(a)
hellopython
>>> id(a)
2552494593072
str确实时不可改变的,但是这里a+"pytho"得到的是一个新的字符串,因为a的地址改变了,所有并没有违背str的值的不可改变的性质
>>> "python"[0]
'p'
>>> "python"[0] = "a"
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
"python"[0] = "a"
TypeError: 'str' object does not support item assignment
把python的第一个字母改为a的时候会报错,因为str不可改变。
扩展序列赋值
L = [1, 2, 3, 4, 5]
a, *b, c = L
print(a, b, c)
流程控制
课外知识:通过字典来调用函数
>>>def add(x):
print(x+10)
>>>operation = {
'add' : add,
'update' : lambda: x: print(x*2),
'delete' : lambda x: print(x*3)
}
>>>operation.get('delete')(10)
30
enumerate()函数用法:
>>>s = 'hello world'
>>>for i,j in enumerate(s):
>>> print('({}) {}'.format(i, j))
(0) h
(1) e
(2) l
(3) l
(4) o
(5)
(6) w
(7) o
(8) r
(9) l
(10) d