第 4 章 · 數據類型、運算符與數字

1. 基本數據類型

Python 3 有六種標準型別:Number(數字)、String(字串)、List(列表)、Tuple(元組)、Set(集合)、Dictionary(字典)。

變數本身沒有型別——型別屬於它所指的物件,可用 type() 查詢。

Python 3 六種標準型別不可變 immutableNumber(數字)String(字串)Tuple(元組)可變 mutableList(列表)Dictionary(字典)Set(集合)「可變」指修改資料時會不會改變變數的引用位址
圖:六種標準型別與可變/不可變分類。

2. Number(數字)

支援 int、float、bool、complex:

a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))   # int float bool complex

2.1 數字型別

數值型別不可變:改變值等於重新分配記憶體。

2.2 數字運算

print(2 + 2)            # 4
print(50 - 5*6)         # 20
print((50 - 5*6) / 4)   # 5.0
print(17 / 3, 17 // 3, 17 % 3)   # 5.66.. 5 2
print(5 ** 2)           # 25

2.3 型別轉換

把型別名稱當函式即可:int(x)、float(x)、complex(x)、complex(x, y)。

int(1.0)   # 1

3. String(字串)

s = 'Yes, he doesn\'t'
print(s, type(s), len(s))
print('C:\\some\\name')     # 反斜線會轉義
print(r'C:\\some\\name')    # 原始字串
word = 'Python'
print(word[0], word[-1])
print('ilovepython'[1:5])   # love

4. List(列表)

a = ['him', 25, 100, 'her']
a[0] = 9          # 修改
del a[0]          # 刪除
print(a + [6, 7, 8])

5. Tuple(元組)

tup = (1, 2, 3, 4, 5, 6)
print(tup[0], tup[1:5])
tup[0] = 11   # 非法:tuple 不支援元素賦值

6. Set(集合)

student = {'Tom', 'Jim', 'Mary', 'Tom'}   # 自動去重
a = set('abracadabra'); b = set('alacazam')
print(a - b, a | b, a & b, a ^ b)

7. Dictionary(字典)

tel = {'Jack': 1557, 'Tom': 1320}
print(tel['Jack'])        # 取值
tel['Mary'] = 4127        # 新增/修改
del tel['Tom']            # 刪除
sorted(tel.keys())        # 依 key 排序

8. 運算符(Operator)

8.1 算術運算符

運算符 說明
+ - * / 加、減、乘、除(/ 回傳浮點數)
% 取餘
** 次方
// 取整除法

8.2 比較運算符

==、!=、<、>、<=、>=;結果為 True/False(首字母大寫)。

8.3 賦值運算符

=、+=、-=、*=、/=、%=、**=、//=(如 c += a 等於 c = c + a)。

8.4 成員運算符

in/not in:判斷元素是否存在於序列中。

8.5 身分運算符

is/is not:判斷兩個變數是否指向同一個物件。

8.6 運算符優先級(高 → 低)

優先 運算符
1 ()、[]、{}(群組、索引、字典)
2 x[i]、x[i:j]、x(...)、x.attr
3 **
4 +x、-x、~x
5 *、/、//、%、@
6 +、-
7 <<、>>
8 &
9 ^
10 |
11 ==、!=、<、<=、>、>=、in、is
12 not
13 and、or