Python 的運算符
本文解釋了 Python 中的運算符。
YouTube Video
Python 的運算符
Python 有各種運算符,大致可以分為以下幾類。我們將講解每種類型的代表性運算符。
算術運算符
算術運算子是用於執行數字計算的運算子。
| 運算子 | 意義 | 範例 |
|---|---|---|
+ |
加法 | 3 + 2 → 5 |
- |
減法 | 3 - 2 → 1 |
* |
乘法 | 3 * 2 → 6 |
/ |
除法(結果總是浮點數) | 3 / 2 → 1.5 |
// |
整數除法(取地板值) | 3 // 2 → 1 |
% |
取餘數(模運算) | 3 % 2 → 1 |
** |
次方運算 | 3 ** 2 → 9 |
1a = 10
2b = 3
3
4print(f"{a} + {b} = {a + b}") # Addition
5print(f"{a} - {b} = {a - b}") # Subtraction
6print(f"{a} * {b} = {a * b}") # Multiplication
7print(f"{a} / {b} = {a / b}") # Division (float)
8print(f"6 / 3 = {6 / 3}") # Division (float)
9print(f"{a} // {b} = {a // b}") # Floor Division
10print(f"{a} % {b} = {a % b}") # Modulo (remainder)
11print(f"{a} ** {b} = {a ** b}") # Exponentiation- 除了四則基本運算外,Python 還提供了除法(
/)、整數除法(//)、取餘數(%)以及冪次(**)等運算符。即使是整數相除,除法也會返回浮點數。
賦值運算子
賦值運算子用來將值指定給變數。
| 運算子 | 意義 | 範例 |
|---|---|---|
= |
賦值 | x = 5 |
+= |
加後賦值 | x += 2 → x = x + 2 |
-= |
減後賦值 | x -= 2 → x = x - 2 |
*= |
乘後賦值 | x *= 2 → x = x * 2 |
/= |
除後賦值 | x /= 2 → x = x / 2 |
//= |
整數除法(取地板值) | x //= 2 → x = x // 2 |
%= |
餘數結果賦值 | x %= 2 → x = x % 2 |
**= |
次方結果賦值 | x **= 2 → x = x ** 2 |
&= |
使用 AND 並賦值 | x &= 0b1010 → x = x & 0b1010 |
|= |
使用 OR 並賦值 | x | = 0b0011→x = x | 0b0011 |
^= |
使用 XOR 並賦值 | x ^= 0b0101 → x = x ^ 0b0101 |
<<= |
左移後賦值 | x <<= 2 → x = x << 2 |
>>= |
右移後賦值 | x >>= 1 → x = x >> 1 |
:= |
賦值運算式(海象運算子) | if (n := len(data)) > 10: → 在判斷條件時同時將值賦給 n |
1x = 5 # x = 5
2
3x += 3 # x = x + 3
4x -= 2 # x = x - 2
5x *= 4 # x = x * 4
6x /= 3 # x = x / 3
7x //= 2 # x = x // 2
8x %= 5 # x = x % 5
9x **= 3 # x = x ** 3
10
11x = 0b1100 # x = 0b1100 (12)
12
13x &= 0b1010 # x = x & 0b1010
14x |= 0b0011 # x = x | 0b0011
15x ^= 0b0101 # x = x ^ 0b0101
16x <<= 2 # x = x << 2
17x >>= 1 # x = x >> 1
18
19print(bin(x)) # Display in binary
20print(x) # Display in decimal
21
22# Walrus operator
23if (n := len("hello")) > 3:
24 print(f"Length is {n}")- 賦值運算符可以結合標準賦值與各種運算符,將結果賦值。
- 海象運算子(
:=)是 Python 3.8 及以後版本提供的賦值運算式。 - 標準賦值只能作為語句使用,而海象運算子允許在運算式中進行賦值。
比較運算符
比較運算子用於比較值並返回True或False。
| 運算子 | 意義 | 範例 |
|---|---|---|
== |
等於 | 3 == 3 → True |
!= |
不等於 | 3 != 4 → True |
> |
大於 | 5 > 2 |
< |
小於 | 5 < 2 |
>= |
大於或等於 | 5 >= 5 |
<= |
小於或等於 | 3 <= 4 |
1a = 10
2b = 20
3
4# Equal to (==)
5print(f"{a} == {b} -> {a == b}") # False: a and b are not equal
6print(f"3 == 3.0 -> {3 == 3.0}") # True: int and float with the same value are equal
7print(f"3 == '3' -> {3 == '3'}") # False: different types (int vs str)
8print(f"True == 1 -> {True == 1}") # True: True is equivalent to 1
9print(f"False == 0 -> {False == 0}") # True: False is equivalent to 0
10print(f"None == 0 -> {None == 0}") # False: None is not equal to 0
11
12# Not equal to (!=)
13print(f"{a} != {b} -> {a != b}") # True: a and b are not equal
14
15# Greater than (>)
16print(f"{b} > {a} -> {b > a}") # True: 20 > 10
17
18# Less than (<)
19print(f"{a} < {b} -> {a < b}") # True: 10 < 20
20
21# Greater than or equal to (>=)
22print(f"{a} >= 10 -> {a >= 10}") # True: a is greater than or equal to 10
23
24# Less than or equal to (<=)
25print(f"{a} <= 10 -> {a <= 10}") # True: a is less than or equal to 10- 比較運算符用於比較兩個值的大小或相等性,並返回
True或False作為結果。 - 在 Python 中,比較不同資料型態時需要小心。有些型態雖然可以互相比較,但結果可能不如預期。
邏輯運算符
邏輯運算子用於組合邏輯表達式。
| 運算子 | 意義 | 範例 |
|---|---|---|
and |
兩者皆為 True 時,結果為 True | True and False → False |
or |
任一為 True 時,結果為 True | True or False → True |
not |
布林值取反 | not True → False |
1x = 10
2print(x > 5 and x < 20) # True
3print(x < 5 or x > 20) # False
4print(not x == 10) # Falseand是邏輯運算符,僅當左右兩邊的條件都為True時才返回True。or是邏輯運算符,只要左右任一條件為True時就會返回True。not是邏輯運算符,用來反轉條件的真假值。如果是 True,則變成 False;如果是 False,則變成 True。
邏輯運算子的優先順序
運算子有優先順序。這是決定在運算式中哪個運算子先被計算的規則。邏輯運算子的計算順序為:not、and,然後是 or。
1result = True or False and False
2print(result) # True
3
4result = (True or False) and False
5print(result) # Falseたとえば、
在第一個例子中,會先計算 and,所以 False and False 變成 False,結果 True or False 就變成 True。你也可以透過加上括號來改變計算的順序,如同在第二個例子中所示。
位運算子
位元運算子用於執行位元級的操作。
| 運算子 | 意義 | 範例 |
|---|---|---|
& |
位元 AND(且)運算 | 5 & 3 → 1 |
| |
位元 OR(或)運算 | 5 | 3→7 |
^ |
位元互斥或(XOR)運算 | 5 ^ 3 → 6 |
~ |
位元反向(NOT)運算 | ~5 → -6 |
<< |
左移位運算 | 5 << 1 → 10 |
>> |
右移位運算 | 5 >> 1 → 2 |
1# Sample code for bitwise operators
2
3# Define two integers
4a = 5 # Binary: 0101
5b = 3 # Binary: 0011
6
7# Bitwise AND
8result_and = a & b # Binary: 0001 -> Decimal: 1
9print(f"{a} & {b} = {result_and}")
10
11# Bitwise OR
12result_or = a | b # Binary: 0111 -> Decimal: 7
13print(f"{a} | {b} = {result_or}")
14
15# Bitwise XOR
16result_xor = a ^ b # Binary: 0110 -> Decimal: 6
17print(f"{a} ^ {b} = {result_xor}")
18
19# Bitwise NOT (inverting bits)
20result_not = ~a # Binary: -(0101 + 1) -> Decimal: -6
21print(f"~{a} = {result_not}")
22
23# Left shift
24shift_left = a << 1 # Binary: 1010 -> Decimal: 10
25print(f"{a} << 1 = {shift_left}")
26
27# Right shift
28shift_right = a >> 1 # Binary: 0010 -> Decimal: 2
29print(f"{a} >> 1 = {shift_right}")- 你可以進行位元 AND、OR、XOR、NOT 運算,以及位移操作。你也可以將它們和賦值運算符(如
&=)結合使用。
成員運算子
成員運算子用於列表和字典等集合。
1x = [1, 2, 3]
2y = 2
3z = 4
4
5print("y in x : ", y in x) # Result is True
6print("z in x : ", z in x) # Result is False
7
8print("y not in x : ", y not in x) # Result is False
9print("z not in x : ", z not in x) # Result is True
10
11text = "hello world"
12print("'world' in 'hello world' : ", "world" in text) # True
13print("'python' not in 'hello world' : ", "python" not in text) # True- 運算子
in用於判斷指定值是否包含在像是串列或字串這樣的序列中,或者是像字典這樣的集合中。 - 運算子
not in用於判斷指定值是否不包含在序列或集合中。
身份運算子
身分運算子用於檢查物件的身分。
1x = [1, 2, 3]
2y = x
3z = x.copy()
4
5print("x is y : ", x is y) # Result is True
6print("x is z : ", x is z) # Result is False
7
8print("x is not y : ", x is not y) # Result is False
9print("x is not z : ", x is not z) # Result is True
10
11print("x == y : ", x == y) # Result is True
12print("x == z : ", x == z) # Result is Trueis運算符用來檢查兩個物件是否為同一個物件(即是否指向相同的記憶體位置)。is not運算符用來檢查兩個物件是否為不同的物件。- 例如,
x is y不同於x == y,它檢查的是物件的識別(身份),而不是值的相等性。
型別檢查
在 Python 中,你可以使用 isinstance() 函數來檢查一個值是否屬於特定型別。你也可以用 type() 函數來檢查變數的確切型別。雖然這些不是運算子,但它們是進行型別檢查的基本機制。
1x = 10
2print(isinstance(x, int)) # True
3
4y = "hello"
5print(isinstance(y, str)) # True
6
7z = [1, 2, 3]
8print(isinstance(z, list)) # True
9
10print(type(10)) # <class 'int'>
11print(type("hello")) # <class 'str'>
12
13print("isinstance(3, int) : ", isinstance(3, int)) # True
14print("type(3) is int : ", type(3) is int) # True
15print("type(True) is bool : ", type(True) is bool) # Trueisinstance()是用來檢查某個物件是否為指定類別或其子類別的實例的函數。type()是返回物件精確類型(類別)的函數。這通常用於你想嚴格進行型別比較的時候。isinstance()會考慮繼承關係,而type()則是檢查完全相同的型別。
總結
在使用每個運算子時,需要根據其用途和類型進行適當選擇。由於 Python 是一種動態類型語言,運算結果可能會根據計算值的類型而有所不同。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。