這篇文章是閱讀Asabeneh的30 Days Of Python: Day 3 - Operators後的學習筆記與心得。
大致上的概念與JavaScript(以下簡稱JS)差不多:
運算子 | 範例 | 等同於 |
---|---|---|
= | 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 &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
從&=
開始是跟位元比對有關,這部份不會在這章節中說明。
運算子 | 名稱 | 範例 |
---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x % y |
% | Modulus | x >= y |
** | Exponentiation | x ** y |
// | Floor division | x // y |
大部分與JS相同+
、-
、*
、/
、餘數運算子%
和指數運算子**
;但Python有一個整數除法運算子//
,這個在JS中沒有(在JS是註解):
print(1 + 2) # 3
print(1 - 2) # -1
print(1 * 2) # 2
print(1 / 2) # 0.5
print(1 % 2) # 1
print(2 ** 3) # 8
print(5 // 2) # 2
跟JS一樣Python也會有IEEE 754浮點數運算誤差的問題
print(0.1 + 0.2) # 0.30000000000000004
運算子 | 名稱 | 範例 |
---|---|---|
== | Equal | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
跟JS比起來就沒有===
這種要考慮型別的了,Python就是強型別,可以想每個比較都是JS的===
:
console.log(1 == "1") // true
console.log(1 === "1") // false
print(1 == "1") # False
除了上述的比較運算子之外,Python還有:
True
。is
相反True
。in
相反print(1 is 1) # True
print(1 is not 2) # True
print("H" in "Hello") # True - H found in the string
print("E" in "Hello") # False - There is no uppercase E
print("Hello" in "Hello World!") # True
print("world" not in "Hello World!") # True - The word is capitalize
這邊is
要強調參照的原因與JS的Paste by ref和Paste by value的概念一樣:python - Is there a difference between "==" and "is"? - Stack Overflow
name = "John"
user = "john"
name.lower() # "john"
print(name.lower() == user) # True
print(name.lower() is user) # False
print("John".lower() == "john") # True
print("John".lower() is "john") # False
而且還有一些是Python實踐上的細節,小的整數(int)在Python中會被快取(cache)起來:
n = 5
print(n is 5) # True
m = 5000
print(m is 5000) # False
print(1000 is 10**3) # True in Python 3.7
x = 10
print(1000 is x ** 3) # False
y = 1
print(1 is y ** 2) # True
print(1000 is 1e3) # False - 1e3 is float type which is 1000.0
可以透過id(<value>)來確認他們的參照
Operators and Expressions in Python – Real Python
運算子 | 描述 | 範例 |
---|---|---|
and | 如果宣告都為True ,回傳True |
x < 5 and x < 10 |
or | 如果其中一個宣告為True ,回傳True |
x < 5 or x < 4 |
not | 反轉結果,回傳False 如果結果為True |
not(x < 5 and x < 10) |
原文是用statement,但這邊看起比較像是expression
-- What is the difference between an expression and a statement in Python? | stackoverflow
跟JS差不多:
print(3 > 2 and 4 > 3) # True
print(3 < 2 or 4 > 3) # True
print(not(3 > 2 and 4 > 3)) # False
print(not(3 < 2 or 4 > 3)) # False
也跟JS差不多,and
也會回傳最後一個Truthy
值如果這個宣告為True
,否則會回傳第一個Falsy
值:
print(3 and 4) # 4
print(0 and 4) # 0
or
會回傳最後一個Falsy
值如果這個宣告為False
,否則會回傳第一個Truthy
值,就是跟and
相反:
print(4 or 0) # 4
print(0 or False) # False