iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
佛心分享-IT 人自學之術

Python 學習筆記系列 第 14

筆記Day14:條件判斷(上)

  • 分享至 

  • xImage
  •  

今天要介紹的是條件判斷,條件判斷在流程控制中是最基礎也最重要的工具,它可以根據不同情況操作不同的動作。

  • 條件執行:當某個表達式為True時,才會執行。
  • 重複執行:只要某個表達式為True程式碼將會重複執行。

在 Python 中使用 if 等相關函式時需要注意縮排,如同先前介紹的,Python 中非常注重縮排,否則很容易出現錯誤。
IndentationError: unexpected indent (<string>, line 1)

基本語法與流程

if / elif / else三本柱所組成,if判斷結果為布林值,只要為True就會進入該區塊。

以下讓我們分別對這三本柱拆解一下吧!

  • if
a = 8
if a > 0:
    print("正數")
  • elif
    elif可以接很多個都不是問題,但想想這樣做法是不是很醜?
    可以思考一下有什麼方式可以改善,後續會提到。
score = 77
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
  • else
a = -1
if a > 0:
    print("正數")
else:
    print("負數")

如果將三本柱整合起來呢?

weather = "rainy"
if weather == "rainy":
    print("fine")
elif weather == "sunny":
    print("go outside")
else:
    print("go home")

常用比較與運算子

  • 比較運算子:==!=><>=<=,不會改變變數的值,單純比較後回傳布林值。
a = 10
b = 5

print(a == b)   # False,因為 10 不等於 5
print(a != b)   # True,因為 10 確實不等於 5
print(a > b)    # True,因為 10 大於 5
print(a < b)    # False,因為 10 不小於 5
print(a >= 10)  # True,因為 10 等於 10
print(b <= 5)   # True,因為 5 等於 5
  • 身份比較:isis not,這邊值得注意的是,在檢測是否為None時,要使用的是is None而不是== None
    根據範例可以看到x is y會回傳False是因為本身儲存在記憶體時位置不相同,儘管儲存內容是一樣的,但實際上因為位置不同而表示他們是獨立的個體。
x = [1, 2, 3]
y = [1, 2, 3]

print(x == y)      # True,因為內容相等
print(x is y)      # False,因為 x 和 y 雖然內容一樣,但它們是不同的物件

# 檢查 None 的方式
value = None
print(value is None)     # True
print(value == None)     # True(雖然可用,但不推薦)
  • 邏輯運算:andornot
age = 20
is_student = True

# and:兩個條件都要成立
print(age >= 18 and is_student)  # True,因為年齡 >= 18 且是學生

# or:只要有一個條件成立
print(age < 18 or is_student)    # True,因為雖然年齡不小於 18,但 is_student 是 True

# not:反轉布林值
print(not is_student)            # False,因為 is_student 原本是 True
  • 成員運算:innot in,用於檢查是否在其中
result = [1, 2, 3]
print(2 in result) # True

那麼今天就介紹到這,明天見ㄅㄅ!


上一篇
筆記Day13:迴圈 Loop
下一篇
筆記Day15:條件判斷(下)
系列文
Python 學習筆記19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言