目錄
- 簡單示例
- 條件測試
- 檢查是否相等與不等
- 檢查多個條件
- 檢查特定的值是否在/不在列表中
- 布爾表達式
- if語句
- 簡單的if語句
- if-else語句
- if-elif-else語句
- 使用if語句處理列表
- 檢查特殊元素
- 確定列表非空
- 使用多個列表
- 總結
if 語句是Python編程中最基本也是最重要的控制結構之一。它允許程序根據不同的條件執行不同的代碼塊,是實現程序邏輯判斷的核心工具。我們從一個簡單的示例開始。
簡單示例
cars = ['audi', 'bmw', 'volvo', 'toyota']
for car in cars:if car == 'bmw':print(car.upper())else:print(car.title())
在上面的例子中,大多數汽車品牌都應以首字母大寫的方式打印其名稱,但是汽車品牌 ‘bmw’ 應以全大寫的方式打印。上述示例應用 if
語句,成功將 ‘bmw’ 字段從 cars 列表中識別并處理。
條件測試
條件測試是 if 語句的核心,每條 if 語句都是一個值為 True 或 False 的表達式,這種表達式即稱為條件測試。它決定了程序的執行路徑,而Python,則提供了多種方式來構建條件測試。
檢查是否相等與不等
最常見的條件測試是檢查兩個值是否相等或不等:
# 相等檢查
name = "Alice"
if name == "Alice":print(f"你好,{name}!")# 不等檢查
temperature = 25
if temperature != 30:print("溫度不是30度")# 忽略大小寫的字符串比較
city = "Beijing"
if city.lower() == "beijing":print("歡迎來到北京!")
注意事項:
- 使用
==
進行相等比較,而不是單個=
(賦值運算符) - 字符串比較是區分大小寫的,可以使用
.lower()
或.upper()
方法進行不區分大小寫的比較
檢查多個條件
Python使用 and
、or
和 not
操作符來組合多個條件:
# 使用 and:所有條件都必須為真
age = 25
income = 50000
if age >= 18 and income >= 30000:print("符合貸款條件")# 使用 or:至少一個條件為真
weather = "晴天"
temperature = 22
if weather == "晴天" or temperature > 20:print("今天適合外出")# 使用 not:條件為假時執行
is_weekend = False
if not is_weekend:print("今天是工作日")# 復雜條件組合
score = 85
attendance = 90
if (score >= 80 and attendance >= 85) or score >= 95:print("獲得優秀成績!")
- 使用 and:所有條件都必須為真
- 使用 or:至少一個條件為真
- 使用 not:條件為假時執行
檢查特定的值是否在/不在列表中
使用in
和not in
關鍵字可以方便地檢查元素是否存在于序列中:
# 檢查值是否在列表中
favorite_fruits = ['蘋果', '香蕉', '橙子', '葡萄']
fruit = '蘋果'if fruit in favorite_fruits:print(f"{fruit}是我喜歡的水果之一")# 檢查值是否不在列表中
banned_users = ['user123', 'spammer', 'troll']
username = 'alice'if username not in banned_users:print("歡迎登錄!")# 在字符串中查找子字符串
message = "Python是一門強大的編程語言"
if "Python" in message:print("這條消息提到了Python")# 檢查字典中的鍵
user_info = {'name': '張三', 'age': 25, 'city': '上海'}
if 'email' not in user_info:print("用戶信息中缺少郵箱")
布爾表達式
下面我們繼續深入,布爾表達式。布爾表達式直接返回True或False值,可以直接用作條件:
# 布爾變量
is_student = True
if is_student:print("學生價格優惠")# 函數返回布爾值
def is_even(number):return number % 2 == 0num = 10
if is_even(num):print(f"{num}是偶數")# 列表的布爾值:空列表為False,非空列表為True
shopping_list = []
if shopping_list:print("購物清單不為空")
else:print("購物清單是空的")# 數字的布爾值:0為False,非0為True
balance = 0
if balance:print("賬戶有余額")
else:print("賬戶余額為零")
在很多實際示例中,應用布爾表達式進行判斷,是一種高效的、易讀易懂的方式。
if語句
簡單的if語句
if語句有很多種,具體選擇哪一種取決于要測試的條件數。簡單的 if
語句只包含一個條件和對應的執行操作代碼塊:
# 基本語法
password = "123456"
if len(password) < 8: # 條件print("密碼太短,請使用至少8個字符") # 執行操作代碼塊# 多行代碼塊
score = 95
if score >= 90: # 條件print("優秀成績!")print(f"你的分數是:{score}")print("繼續保持!")# 嵌套if語句
user_type = "admin"
is_logged_in = Trueif is_logged_in:print("用戶已登錄")if user_type == "admin":print("管理員權限已激活")
if-else語句
有時,我們不僅需要在條件測試時執行一個操作,在沒有通過時也需指定另一個操作。if-else
語句提供了條件為假時的備選執行路徑:
# 基本if-else結構
age = 16
if age >= 18:print("可以投票")
else:print("還不能投票")# 處理用戶輸入
number = int(input("請輸入一個數字: "))
if number > 0:print("這是一個正數")
else:print("這是零或負數")# 字符串處理
username = input("請輸入用戶名: ").strip()
if username:print(f"歡迎,{username}!")
else:print("用戶名不能為空")
當然,if-else
語句只能用在邏輯上或真或假的情況下。
if-elif-else語句
當需要檢查多個條件時,if-elif-else
語句提供了清晰的解決方案:
# 成績等級劃分
score = 78
if score >= 90:grade = 'A'
elif score >= 80:grade = 'B'
elif score >= 70:grade = 'C'
elif score >= 60:grade = 'D'
else:grade = 'F'print(f"成績:{score},等級:{grade}")# 季節判斷
month = 7
if month in [12, 1, 2]:season = "冬季"
elif month in [3, 4, 5]:season = "春季"
elif month in [6, 7, 8]:season = "夏季"
elif month in [9, 10, 11]:season = "秋季"
else:season = "無效月份"print(f"{month}月是{season}")# 復雜的條件判斷
age = 25
income = 45000
credit_score = 720if age >= 21 and income >= 50000 and credit_score >= 700:loan_status = "批準 - 優惠利率"
elif age >= 18 and income >= 30000 and credit_score >= 650:loan_status = "批準 - 標準利率"
elif age >= 18 and income >= 20000:loan_status = "需要擔保人"
else:loan_status = "拒絕"print(f"貸款狀態:{loan_status}")
當然,讀者需要注意,else
模塊非必須,即條件判斷語句可忽略 else
代碼塊。
使用if語句處理列表
列表處理是Python編程中的常見任務,結合if語句可以實現強大的數據篩選和處理功能,且一般對于列表的操作,都會與循環 for
結合在一起,從而輪詢的方式實現對整個列表的條件測試。
檢查特殊元素
在處理列表時,經常需要對特定元素進行特殊處理:
# 處理VIP用戶
users = ['alice', 'bob', 'admin', 'charlie', 'guest']print("用戶登錄狀態:")
for user in users:if user == 'admin':print(f"{user}: 管理員 - 全部權限")elif user == 'guest':print(f"{user}: 訪客 - 只讀權限")else:print(f"{user}: 普通用戶 - 基本權限")# 處理訂單狀態
orders = [{'id': 1, 'status': 'pending', 'amount': 100},{'id': 2, 'status': 'completed', 'amount': 250},{'id': 3, 'status': 'cancelled', 'amount': 80},{'id': 4, 'status': 'pending', 'amount': 150}
]print("\n訂單處理:")
for order in orders:if order['status'] == 'pending':print(f"訂單 {order['id']}: 等待處理,金額 {order['amount']}元")elif order['status'] == 'completed':print(f"訂單 {order['id']}: 已完成,收入 {order['amount']}元")elif order['status'] == 'cancelled':print(f"訂單 {order['id']}: 已取消,退款 {order['amount']}元")# 數據清洗示例
raw_data = [1, '', 0, 'hello', None, 42, [], 'world', False]
cleaned_data = []for item in raw_data:if item: # 過濾掉"假值"cleaned_data.append(item)elif item == 0: # 保留數字0cleaned_data.append(item)print(f"\n原始數據:{raw_data}")
print(f"清洗后數據:{cleaned_data}")
提示:‘’
、0
、None
、[]
、False
都為假值,但在 Python 中,為了方便數值計算,bool 類型是 int 類型的子類。True
等于 1,False
等于 0。所以 False == 0
的結果是 True
。
確定列表非空
在處理列表之前,檢查列表是否為空是一個好習慣:
# 基本的空列表檢查
shopping_cart = []if shopping_cart:print("購物車商品:")for item in shopping_cart:print(f"- {item}")print(f"總計 {len(shopping_cart)} 件商品")
else:print("購物車是空的,快去添加商品吧!")# 更復雜的列表處理
def process_scores(scores):if not scores:return "沒有成績數據"total = sum(scores)average = total / len(scores)highest = max(scores)lowest = min(scores)return f"""
成績統計:
- 總分:{total}
- 平均分:{average:.2f}
- 最高分:{highest}
- 最低分:{lowest}
- 學生人數:{len(scores)}
"""
使用多個列表
在實際應用中,經常需要同時處理多個列表:
# 學生信息管理
students = ['張三', '李四', '王五', '趙六', '陳七']
scores = [85, 92, 78, 96, 88]
grades = ['B', 'A', 'C', 'A', 'B']# 確保所有列表長度一致
if len(students) == len(scores) == len(grades):print("學生成績報告:")print("-" * 40)for i in range(len(students)):student = students[i]score = scores[i]grade = grades[i]# 根據成績給出評價if score >= 90:comment = "優秀"elif score >= 80:comment = "良好"elif score >= 70:comment = "中等"elif score >= 60:comment = "及格"else:comment = "不及格"print(f"{student:6s} | 分數:{score:3d} | 等級:{grade} | 評價:{comment}")
else:print("錯誤:學生信息數據不完整")
總結
if語句是Python編程的基石,掌握其各種用法對于編寫高效、清晰的代碼至關重要。本文涵蓋了:
- 基礎概念:從簡單示例入手,理解if語句的基本工作原理
- 條件測試:掌握各種條件判斷方式,包括相等性檢查、邏輯運算符、成員測試和布爾表達式
- 語句結構:深入了解if、if-else和if-elif-else三種基本結構
- 實際應用:學會在列表處理中應用if語句,解決實際編程問題
通過大量的實例代碼,我們看到if語句在數據處理、用戶交互、條件判斷等場景中的強大功能。熟練掌握這些技能將為你的Python編程之路奠定堅實的基礎。
最后,記住,良好的編程實踐包括:
- 使用清晰、有意義的變量名
- 保持代碼縮進一致
- 在復雜條件中使用括號提高可讀性
- 處理好邊界情況(如空列表、None值等)
- 編寫簡潔而富有表現力的條件語句
2025.09 西三旗