運算優先順序

了解運算子的執行順序可以避免錯誤。

優先順序表 (由高到低)

優先順序 運算子
1 () 括號
2 ** 次方
3 +x -x ~x 正負號
4 * / // %
5 + -
6 < <= > >= != ==
7 not
8 and
9 or

範例

# 先乘除後加減
result = 2 + 3 * 4     # 14

# 次方優先
result = 2 ** 3 ** 2   # 512 (3**2=9, 2**9=512,次方從右到左)

# 括號最優先
result = (2 + 3) * 4   # 20

邏輯運算順序

# not > and > or
result = True or False and False  
# 先算 False and False = False
# 再算 True or False = True

result = not True or False
# 先算 not True = False
# 再算 False or False = False

建議

# 使用括號讓程式碼更清晰
# 不好
if a > b and c < d or e == f:
    pass

# 好
if (a > b and c < d) or (e == f):
    pass

練習

計算 2 + 3 * 4 ** 2 - 10 // 3 的結果

💻 程式碼編輯器
📤 執行結果
等待執行...
← 上一課 完成本等級 ✓