Python 中的運算子函式
在 Python 中,有一些額外的標準庫方法用於數學運算,例如算術、邏輯、關係、位運算等操作。這些方法可以在 **operator** 模組中找到。
要使用它,首先我們需要匯入 operator 標準庫模組。
import operator
在本節中,我們將瞭解一些用於位運算和容器運算的運算子函式。
算術運算
首先,我們將瞭解算術運算函式。它們如下所示。
| 序號 | 函式及描述 |
|---|---|
| 1 | add(x,y) add() 方法用於將兩個數字 x 和 y 相加。它執行簡單的加法運算。它類似於 x + y 操作。 |
| 2 | sub(x,y) sub() 方法用於從 x 中減去 y。它類似於 x - y 操作。 |
| 3 | mul(x,y) mul() 方法用於將兩個數字 x 和 y 相乘。它類似於 x * y 操作。 |
| 4 | truediv(x,y) truediv() 方法用於查詢 x 除以 y 後的結果。此方法可能會返回分數作為結果。它類似於 x / y 操作。 |
| 5 | floordiv(x,y) floordiv() 方法用於查詢 x/y 的商。它類似於 x // y 操作。 |
| 6 | mod(x,y) mod() 方法用於獲取 x/y 的餘數。它類似於 x % y 操作。 |
| 7 | pow(x,y) pow() 方法用於查詢 x ^ y。它類似於 x ** y 操作。 |
示例程式碼
#Arithmetic Operators
import operator
print('Add: ' + str(operator.add(56, 45)))
print('Subtract: ' + str(operator.sub(56, 45)))
print('Multiplication: ' + str(operator.mul(56, 45)))
print('True division: ' + str(operator.truediv(56, 45))) # same as a / b
print('Floor division: ' + str(operator.floordiv(56, 45))) #same as a // b
print('Mod: ' + str(operator.mod(56, 45))) #same as a % b
print('pow: ' + str(operator.pow(5, 3)))
輸出
Add: 101 Subtract: 11 Multiplication: 2520 True division: 1.2444444444444445 Floor division: 1 Mod: 11 pow: 125
關係運算
operator 模組還包含關係運算符,如 <、<=、>、>=、==、!=。
運算子函式如下所示:
| 序號 | 函式及描述 |
|---|---|
| 1 | lt(x,y) lt() 方法用於檢查數字 x 是否小於 y。它類似於 x < y 操作。 |
| 2 | le(x,y) le() 方法用於檢查數字 x 是否小於或等於 y。它類似於 x <= y 操作。 |
| 3 | eq(x,y) eq() 方法用於檢查數字 x 和 y 是否相等。它類似於 x == y 操作。 |
| 4 | gt(x,y) gt() 方法用於檢查數字 x 是否大於 y。它類似於 x > y 操作。 |
| 5 | ge(x,y) ge() 方法用於檢查數字 x 是否大於或等於 y。它類似於 x >= y 操作。 |
| 6 | ne(x,y) ne() 方法用於檢查數字 x 和 y 是否不相等。它類似於 x != y 操作。 |
示例程式碼
#Relational Operators
import operator
print('Less Than: ' + str(operator.lt(5, 10)))
print('Less Than Equal: ' + str(operator.le(10, 10)))
print('Greater Than: ' + str(operator.gt(5, 5)))
print('Greater Than Equal: ' + str(operator.ge(5, 5)))
print('Equal to: ' + str(operator.eq(12, 12)))
print('Not Equal to: ' + str(operator.ne(15, 12)))
輸出
Less Than: True Less Than Equal: True Greater Than: False Greater Than Equal: True Equal to: True Not Equal to: True
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP