1.只能是字母,數字,下劃線組成
2. 不能以數字開頭
3. 區分大小寫
合法變量名稱:
x =True
_y =False
a =“test”
a_1 =“OK”
a_a_1=“Also OK”
非法變量名稱:
9a=1 # SyntaxError: invalid syntax
區分大小寫,所以x,X 是不同的變量
x=1
y = X +2
import keyword
print(keyword.kwlist)
輸出:
[‘False’, ‘None’, ‘True’, ‘__peg_parser__’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
這些關鍵都不能用做變量名稱
使用type( )函數
整數
a =3
print(a)
print(type(a))
b =123456789087654321
print(b)
print(type(b))
浮點數
pi =3.1415
print(pi)
print(type(pi))
字符串
s1 =‘a’
print(s1)
print(type(s1))
s2 =‘Ritchie Lee’
print(s2)
print(type(s2))
布爾類型
b =True
print(b)
print(type(b))
Null type
x =None
print(x)
print(type(x))
輸出:
3
<class ‘int’>
123456789087654321
<class ‘int’>
3.1415
<class ‘float’>
a
<class ‘str’>
Ritchie Lee
<class ‘str’>
True
<class ‘bool’>
None
<class ‘NoneType’>
a, b, c =1, 2, True
print(a, b, c)
輸出:
1 2 True
如果變量多余賦值值,則會異常
a, b, c =1, 2,
print(a, b, c)
則異常:
a, b, c = 1, 2,
ValueError: not enough values to unpack (expected 3, got 2)
如果賦值數量多余變量:
a, b =1, 2, True
print(a, b)
則異常:
a, b = 1, 2, True
ValueError: too many values to unpack (expected 2)