什么是变量
假设两个list做数学运算
>>> [1,2,3,4,5,6] [1,2,3]
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3,4,5,6] [1,2,3]
TypeError: list indices must be integers or slices, not tuple
//A B,先把A乘以3,然后加上B,最后再加上列表A
>>> [1,2,3,4,5,6]*3+[1,2,3]+[1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4, 5, 6]
>>> A = [1,2,3,4,5,6]
>>> print(A)
[1, 2, 3, 4, 5, 6]
>>> B = [1,2,3]
>>> A*3 + B + A
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4, 5, 6]
变量名的命名规则
变量名命名只能使用字母、数字、下划线
>>> 1a = 2 //变量名的首字母不能是数字
SyntaxError: invalid syntax
>>> A2 = '1'
>>> _2 = '1'
>>> A*B='1'
SyntaxError: can't assign to operator
系统关键字,不能用在变量名中 保留关键字
>>> and = 1
SyntaxError: invalid syntax
>>> if = 2
SyntaxError: invalid syntax
>>> import = 3
SyntaxError: invalid syntax
>>> type = 3 //type不是系统保留关键字,但是不建议作为变量名,否则极易出错
>>> print(type)
3
>>> type = 1
>>> type(1)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
type(1)
TypeError: 'int' object is not callable
>>> 1(1)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
1(1)
TypeError: 'int' object is not callable
python动态语言的特性,声明时不需要指明变量类型
>>> a = '1'
>>> a = 1
>>> a = (1,2,3)
>>> a = {1,2,3}
值类型与引用类型
int、str、tuple是值类型(不可变),list、set、dict是引用类型(可变)
1.int
>>> a = 1
>>> b = a
>>> a = 3
>>> print(b)
1
<