一個expression(表達式或運算式)由operators(運算子或運算符)和operands(運算元)所組成。
e.g. 在 $4+5=9$ 這個算式中,用來運算的 $4$ 和 $5$ 稱為operands;而中間的運算符號 $+$ (加號)則稱為operator。
在Python中,有各種不同的operators;operands和運算出的值也可能是各種不同的資料類型。
Python language supports the following types of operators:
Operator | Name | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder of a / b) | a % b |
** | Exponentiation | a ** b |
// | Floor Division | a // b |
用來比較兩個operand
return a boolean value (True
or False
)
Suppose a = 10
and b = 20
, then:
Operator | Name | Example |
---|---|---|
== | Equal | a == b returns False |
!= | Not Equal | a != b returns True |
> | Greater Than | a > b returns False |
< | Less Than | a < b returns False |
>= | Greater than or Equal to | a >= b returns False |
<= | Less than or Equal to | a <= b returns False |
<aside>
❗ =
is an assignment operator, and ==
is a comparison operator.
</aside>
除了用來比較數字,也可用於其他資料類型。
# 比較number
a = 10
b = 20
print(a == b) # False
# 比較string
a = "Wilson"
b = "Wilson"
print(a == b) # True
==
來確認所有文字是否皆為小寫。Operator | Name | Example | Same as |
---|---|---|---|
= | Assignment | a = b |
a = b |
+= | Addition Assignment | a += b |
a = a + b |
-= | Subtraction Assignment | a -= b |
a = a - b |
*= | Multiplication Assignment | a *= b |
a = a * b |
/= | Division Assignment | a /= b |
a = a / b |
%= | Remainder Assignment | a %= b |
a = a % b |
**= | Exponent Assignment | a **= b |
a = a ** b |
//= | Floor Division Assignment | a //= b |
a = a // b |
+=
, -=
, *=
, /=
, %=
, **=
, //=
稱為syntax sugar (語法糖:使語法更簡潔或更具可讀性的寫法)。