
Python 簡易手冊
單元 17 - 小括弧、逗號與計算優先次序
小括弧 (parentheses) 擁有最高的計算優先次序 (precedence) ,所有被小括弧圍起來的運算式 (expression) 都會被優先運算,其他包括小括弧的運算子 (operator) 計算優先次序如下表
| 種類 | 運算子或運算形式 |
|---|---|
| 小括弧以及串列、字典、集合的字面常數 | (expressions...), [expressions...], {key: value...}, {expressions...} |
| 處理元素以及呼叫 | x[index], x[index:index], x(arguments...), x.attribute |
| 協程 | await x |
| 計算指數 | ** |
| 正負號以及位元非 | +x, -x, ~x |
| 乘、除、取餘數 | *, @, /, //, % |
| 加、減 | +, - |
| 位元位移 | <<, >> |
| 位元且 | & |
| 位元互斥或 | ^ |
| 位元或 | | |
| 比較 | in, not in, is, is not, <, <=, >, >=, !=, == |
| 布林非 | not x |
| 布林且 | and |
| 布林或 | or |
| 條件運算式 | if – else |
| 無名函數 | lambda |
| 指派運算式 | := |
串列 (list) 在單元 39 - 串列介紹,字典 (dictionary) 在單元 41 - 字典介紹,集合在單元 42 - 集合介紹,處理元素 (element) 屬於複合資料型態 (compound data type) 的範疇,呼叫 (call) 是函數 (function) 或建立物件 (object) 的範疇,函數在單元 44 - 函數與 return 陳述介紹,類別 (class) 在單元 54 - 類別介紹,,協程 (coroutine) 在單元 53 - 協程介紹,算術運算子 (arithmetic operator) 在單元 12 - 算術運算子介紹,位元運算子 (bitwise operator) 在單元 16 - 位元運算子介紹,比較運算子 (comparison operator) 在單元 13 - 比較運算子介紹, is 運算子在單元 18 - is 運算子介紹, in 運算子在單元 19 - in 運算子介紹,布林運算子 (Boolean operator) 在單元 11 - 布林運算子介紹,條件運算式 (conditional expression) 在單元 15 - 條件運算式介紹, lambda 陳述 (statement) 在單元 30 - lambda 陳述介紹,指派運算式 (assignment expression) 在單元 14 - 指派陳述與指派運算式介紹。
至於逗號僅作為分隔符號 (delimiter) ,用來分隔變數 (variable) 、數值 (value) 等等,或做為序對 (tuple) 型態的字面常數 (literal) ,因此不在計算的優先次序之列。
序對會在單元 38 - 序對與 Range詳細介紹。
參考資料
- https://docs.python.org/3/reference/lexical_analysis.html#delimiters
- https://docs.python.org/3/reference/expressions.html#operator-precedence
