今天要介紹的是條件判斷
,條件判斷在流程控制中是最基礎也最重要的工具,它可以根據不同情況操作不同的動作。
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
is
、is 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(雖然可用,但不推薦)
and
、or
、not
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
in
、not in
,用於檢查是否在其中result = [1, 2, 3]
print(2 in result) # True
那麼今天就介紹到這,明天見ㄅㄅ!