Python if else 條件判斷
條件判斷讓程式根據不同的條件執行不同的程式碼。
if 語法
if 條件:
# 條件為 True 時執行
age = 20
if age >= 18:
print("You are an adult")
Python 使用縮排來定義程式碼區塊,if 後面的程式碼必須縮排。
if...else
if 條件:
# 條件為 True 時執行
else:
# 條件為 False 時執行
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
輸出:
You are a minor
if...elif...else
當有多個條件要判斷時,使用 elif(else if 的縮寫):
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
輸出:
B
程式會從上到下依序檢查條件,一旦某個條件為 True,就執行該區塊的程式碼,然後跳過剩餘的 elif 和 else。
巢狀 if
if 語句可以巢狀使用:
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license to drive")
else:
print("You are too young to drive")
條件運算
比較運算子
| 運算子 | 說明 |
|---|---|
== | 等於 |
!= | 不等於 |
> | 大於 |
< | 小於 |
>= | 大於等於 |
<= | 小於等於 |
邏輯運算子
| 運算子 | 說明 |
|---|---|
and | 且(兩者都為 True) |
or | 或(其中一個為 True) |
not | 非(反轉布林值) |
age = 25
income = 50000
if age >= 18 and income >= 30000:
print("Eligible for credit card")
if age < 18 or income < 20000:
print("Not eligible")
if not (age < 18):
print("You are an adult")
成員運算子
fruits = ["apple", "banana", "orange"]
if "apple" in fruits:
print("Apple is in the list")
if "grape" not in fruits:
print("Grape is not in the list")
身份運算子
x = None
if x is None:
print("x is None")
if x is not None:
print("x has a value")
三元運算子 (Conditional Expression)
一行寫完簡單的 if-else:
# 語法: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# 等同於
if age >= 18:
status = "adult"
else:
status = "minor"
# 實際應用
score = 75
result = "Pass" if score >= 60 else "Fail"
print(result) # Pass
x = 10
abs_x = x if x >= 0 else -x
print(abs_x) # 10
Truthy 和 Falsy
條件不一定要是布林值,Python 會自動將值轉換為布林值:
# 這些值是 Falsy(會被當作 False)
# False, None, 0, 0.0, "", [], {}, set()
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty") # 會執行這行
my_list = [1, 2, 3]
if my_list:
print("List is not empty") # 會執行這行
實際範例
判斷奇偶數
num = 7
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
判斷閏年
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
找出最大值
a, b, c = 10, 25, 15
if a >= b and a >= c:
max_value = a
elif b >= a and b >= c:
max_value = b
else:
max_value = c
print(f"Maximum: {max_value}") # Maximum: 25
# 當然,Python 有內建函數
print(max(a, b, c)) # 25