Python 運算子 (Operators)
運算子用來對變數和值進行各種運算操作。
算術運算子
用於數學運算:
| 運算子 | 說明 | 範例 | 結果 |
|---|---|---|---|
+ | 加法 | 5 + 3 | 8 |
- | 減法 | 5 - 3 | 2 |
* | 乘法 | 5 * 3 | 15 |
/ | 除法 | 5 / 3 | 1.666... |
// | 整數除法 | 5 // 3 | 1 |
% | 取餘數 | 5 % 3 | 2 |
** | 次方 | 5 ** 3 | 125 |
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
比較運算子
用於比較兩個值,結果是布林值:
| 運算子 | 說明 | 範例 | 結果 |
|---|---|---|---|
== | 等於 | 5 == 3 | False |
!= | 不等於 | 5 != 3 | True |
> | 大於 | 5 > 3 | True |
< | 小於 | 5 < 3 | False |
>= | 大於等於 | 5 >= 3 | True |
<= | 小於等於 | 5 <= 3 | False |
x = 10
y = 5
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
賦值運算子
用於給變數賦值:
| 運算子 | 範例 | 等同於 |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4
print(x) # 4
邏輯運算子
用於組合布林運算:
| 運算子 | 說明 | 範例 |
|---|---|---|
and | 且(兩者都為 True) | True and False → False |
or | 或(其中一個為 True) | True or False → True |
not | 非(反轉布林值) | not True → False |
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
print(not b) # True
# 實際應用
age = 25
has_license = True
if age >= 18 and has_license:
print("可以開車")
成員運算子
用於檢查值是否存在於序列中:
| 運算子 | 說明 |
|---|---|
in | 如果值存在於序列中,回傳 True |
not in | 如果值不存在於序列中,回傳 True |
fruits = ["apple", "banana", "orange"]
print("apple" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # True
# 也可以用在字串
text = "Hello, World!"
print("Hello" in text) # True
print("Python" in text) # False
身份運算子
用於比較兩個物件是否為同一個物件(記憶體位置相同):
| 運算子 | 說明 |
|---|---|
is | 如果兩個變數指向同一物件,回傳 True |
is not | 如果兩個變數指向不同物件,回傳 True |
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True(值相等)
print(a is b) # False(不同物件)
print(a is c) # True(同一物件)
print(a is not b) # True
is 常用於和 None 比較:if x is None: 而不是 if x == None:運算子優先順序
從高到低:
**(次方)*,/,//,%+,-<,<=,>,>=,==,!=notandor
# 使用括號讓優先順序更清楚
result = (2 + 3) * 4 # 20
result = 2 + 3 * 4 # 14(乘法優先)