WEI-CHENG CHEN

概念

當我們希望程式根據「不同情況執行不同結果」時,就需要使用條件判斷!

基本語法結構

if 條件1:
    # 條件1為真,執行這區塊
elif 條件2:
    # 條件1為假且條件2為真
else:
    # 上述條件都不成立時

比較運算符(comparison operator)

![upgit_20240418_1713383314.png 914x287](https://raw.githubusercontent.com/kcwc1029/obsidian-upgit-image/main/2024/04/upgit_20240418_1713383314.png)

邏輯運算(logical operator)

符號 意義 範例
and x > 3 and x < 10
or x < 0 or x > 10
not 取反 not x == 5
![upgit_20240418_1713383360.png 912x229](https://raw.githubusercontent.com/kcwc1029/obsidian-upgit-image/main/2024/04/upgit_20240418_1713383360.png)

位運算符(bitwise operator)

位運算子允許我們對整數的二進位位元進行操作。這些運算子在某些特定情況下非常有用,例如位操作、旗標設定等。

![upgit_20240418_1713383409.png 914x264](https://raw.githubusercontent.com/kcwc1029/obsidian-upgit-image/main/2024/04/upgit_20240418_1713383409.png)
# AND 運算 (`&`)
a = 0b1010  # 10 (十進位)
b = 0b1100  # 12 (十進位)
print(a & b)  # Output: 8 (二進位: 1000)

# OR 運算 (`|`)
# 將對應位元進行 OR 運算,只要有一個對應位元為 1,結果位元就為 1。
a = 0b1010  # 10 (十進位)
b = 0b1100  # 12 (十進位)
print(a | b)  # Output: 14 (二進位: 1110)

# XOR 運算 (`^`)
# 將對應位元進行 XOR 運算,當對應位元不相同時,結果位元為 1。
a = 0b1010  # 10 (十進位)
b = 0b1100  # 12 (十進位)
print(a ^ b)  # Output: 6 (二進位: 0110)

# 取反運算 (`~`)
# 將所有位元取反,即 0 變 1,1 變 0。需要注意的是,取反運算在 Python 中會產生一個負值。
a = 0b1010  # 10 (十進位)
print(~a)  # Output: -11 (二進位: 111..10101)

# 左移運算 (`<<`)
# 將位元向左移動指定的位數,相當於乘以 2 的指定次方。
a = 0b1010  # 10 (十進位)
print(a << 2)  # Output: 40 (二進位: 101000)

# 右移運算 (`>>`)
# 將位元向右移動指定的位數,相當於除以 2 的指定次方。
a = 0b1010  # 10 (十進位)
print(a >> 1)  # Output: 5 (二進位: 101)

Zerojudge

利用 Zerojudge 練習~