目录
一、变量
命名规则:字母、数字、下划线(首字母不能是数字),不能用系统保留关键字
>>> A2 = '1'
>>> 2Q = '1'
SyntaxError: invalid syntax
>>> and = '1'
SyntaxError: invalid syntax
值类型(int、str、元组tuple,不可改变)与引用类型(list、集合set、字典dict,可变)
#值类型,a改变不影响b
>>> a = 1
>>> b = a
>>> a = 3
>>> print(b)
1
>>> a = [1,2,3,4]
#引用类型,a改变b跟着改变
>>> b = a
>>> a[0] = 'x'
>>> print(a,b)
['x', 2, 3, 4] ['x', 2, 3, 4]
>>> a = 'hello'
>>> a = a+'world'
>>> print(a)
helloworld
#得到了新的字符串,不违背不可改变
>>> a[0]
'h'
>>> a[0]='p'
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
a[0]='p'
TypeError: 'str' object does not support item assignment
#试图更改原字符串报错,str不可改变
元组tuple与列表list
#更改列表元素,列表id不变
>>> a = [1,2,3]
>>> id(a)
3168006080392
>>> hex(id(a))
'0x2e19be08788'
>>> a[0] = '1'
>>> id(a)
3168006080392
元组tuple不可更改
>>> a = (1,2,3)
>>> a[0] = '1'
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
a[0] = '1'
TypeError: 'tuple' object does not support item assignment
列表可追加元素,元组不行
>>> b = [1,2,3]
>>> b.append(4)
>>> print(b)
[1, 2, 3, 4]
>>> c = (1,2,3)
>>> c.append(4)
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
c.append(4)
AttributeError: 'tuple' object has no attribute 'append'
可以更改元组中的列表
#取元组嵌套中的元素
>>> a = (1,2,3,[1,2,4])
>>> a[3][2]
4
>>> a = (1,2,3,[12,3,['a','b']])
>>> a[3][2][1]
'b'
#更改元组中的列表元素
>>> a = (1,2,3,[1,2,4])
>>> a[2] = '5'
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a[2] = '5'
TypeError: 'tuple' object does not support item assignment
>>> a[3][2]='5'
>>> print(a)
(1, 2, 3, [1, 2, '5'])
二、运算符号(一)
算术运算符
(+、-、*、/、整数除法//、%、幂次方**)
赋值运算符
(+=、*=、/=、//=、%=、**=等)和C语言类似
例:
>>> b=1
>>> a=2
>>> b+=a
#b+=a等价于b=b+a
>>> print(b)
3
>>> b-=a
>>> print(b)
1
>>> b*=a
>>> print(b)
2
比较运算符
==、!=、>、<、>=、<=,结果返回布尔值bool(True or False),可以比较数字、字符串、元组、列表
#数字
>>> 1>=1
True
#字符串
>>> 'a'>'b'
False
>>> 'abc'<'abd'
True
#元组
>>> (1,2,3)<(1,3,2)
True
#列表
>>> [1,2,3]<[3,2,4]
True