控制結構是編程語言中用來控制程序執行流程的語句。Python提供了條件語句、循環語句等控制結構,讓程序能夠根據不同條件執行不同的代碼塊。
程序執行流程圖:
┌─────────────────────────────────────────────┐
│ 程序控制流程 │
├─────────────────────────────────────────────┤
│ │
│ 順序執行 ──→ 條件分支 ──→ 循環重復 │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ 語句1 if/elif for/while │
│ 語句2 else break │
│ 語句3 continue │
│ │
└─────────────────────────────────────────────┘
條件語句(if, elif, else)
條件語句允許程序根據條件的真假來選擇不同的執行路徑。
1. 基本if語句
# 基本if語句
age = 18if age >= 18:print("你已經成年了!")print("可以投票和工作")print("程序繼續執行")# 帶else的if語句
score = 85if score >= 60:print("考試及格!")
else:print("考試不及格,需要補考")# 嵌套if語句
weather = "晴天"
temperature = 25if weather == "晴天":print("天氣不錯!")if temperature > 30:print("有點熱,記得防曬")elif temperature < 10:print("有點冷,多穿點衣服")else:print("溫度剛好,適合出門")
else:print("天氣不太好")
2. elif語句(多重條件)
# 成績等級判斷
score = 92if score >= 90:grade = "A"comment = "優秀"
elif score >= 80:grade = "B"comment = "良好"
elif score >= 70:grade = "C"comment = "中等"
elif score >= 60:grade = "D"comment = "及格"
else:grade = "F"comment = "不及格"print(f"分數: {score}, 等級: {grade}, 評價: {comment}")# 多條件判斷
username = "admin"
password = "123456"
is_active = Trueif username == "admin" and password == "123456" and is_active:print("登錄成功!")
elif not is_active:print("賬戶已被禁用")
elif username != "admin":print("用戶名錯誤")
else:print("密碼錯誤")
3. 條件表達式(三元運算符)
# 傳統寫法
age = 20
if age >= 18:status = "成年人"
else:status = "未成年人"
print(f"狀態: {status}")# 條件表達式(三元運算符)
age = 16
status = "成年人" if age >= 18 else "未成年人"
print(f"狀態: {status}")# 更復雜的條件表達式
score = 85
result = "優秀" if score >= 90 else "良好" if score >= 80 else "及格" if score >= 60 else "不及格"
print(f"成績: {score}, 評價: {result}")# 實際應用示例
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x if x % 2 == 0 else 0 for x in numbers]
print(f"偶數或0: {even_numbers}")
4. 條件語句的最佳實踐
# ? 好的寫法:使用in操作符
day = "星期六"
if day in ["星期六", "星期日"]:print("今天是周末")# ? 不好的寫法
# if day == "星期六" or day == "星期日":
# print("今天是周末")# ? 好的寫法:利用布爾值的特性
name = ""
if not name: # 空字符串為Falseprint("請輸入姓名")# ? 不好的寫法
# if name == "":
# print("請輸入姓名")# ? 好的寫法:使用is比較None
value = None
if value is None:print("值為空")# ? 不好的寫法
# if value == None:
# print("值為空")# ? 好的寫法:避免深層嵌套
def process_user(user):if not user:return "用戶不存在"if not user.get("active"):return "用戶未激活"if user.get("age", 0) < 18:return "用戶未成年"return "用戶驗證通過"# 測試
user1 = {"name": "張三", "age": 25, "active": True}
user2 = {"name": "李四", "age": 16, "active": True}
user3 = Noneprint(process_user(user1))
print(process_user(user2))
print(process_user(user3))
循環語句
循環語句允許重復執行一段代碼,直到滿足某個條件為止。
1. for循環
for循環用于遍歷序列(如列表、元組、字符串)或其他可迭代對象。
# 遍歷列表
fruits = ["蘋果", "香蕉", "橙子", "葡萄"]
print("水果清單:")
for fruit in fruits:print(f"- {fruit}")# 遍歷字符串
word = "Python"
print("\n字母分解:")
for char in word:print(f"字母: {char}")# 遍歷字典
student = {"姓名": "張三", "年齡": 20, "專業": "計算機科學"}
print("\n學生信息:")
for key, value in student.items():print(f"{key}: {value}")# 只遍歷鍵
print("\n只顯示鍵:")
for key in student.keys():print(key)# 只遍歷值
print("\n只顯示值:")
for value in student.values():print(value)
2. range()函數
# 基本用法
print("0到4:")
for i in range(5):print(i, end=" ")
print()# 指定起始和結束
print("\n1到5:")
for i in range(1, 6):print(i, end=" ")
print()# 指定步長
print("\n偶數0到10:")
for i in range(0, 11, 2):print(i, end=" ")
print()# 倒序
print("\n倒數5到1:")
for i in range(5, 0, -1):print(i, end=" ")
print()# 實際應用:打印乘法表
print("\n九九乘法表:")
for i in range(1, 10):for j in range(1, i + 1):print(f"{j}×{i}={i*j:2d}", end=" ")print() # 換行
3. enumerate()函數
# 獲取索引和值
fruits = ["蘋果", "香蕉", "橙子"]
print("帶索引的遍歷:")
for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")# 指定起始索引
print("\n從1開始編號:")
for index, fruit in enumerate(fruits, start=1):print(f"第{index}個水果: {fruit}")# 實際應用:處理文件行號
lines = ["第一行內容", "第二行內容", "第三行內容"]
for line_num, content in enumerate(lines, start=1):print(f"行{line_num}: {content}")
4. zip()函數
# 同時遍歷多個序列
names = ["張三", "李四", "王五"]
ages = [20, 25, 30]
cities = ["北京", "上海", "廣州"]print("學生信息:")
for name, age, city in zip(names, ages, cities):print(f"{name}, {age}歲, 來自{city}")# 長度不同的序列
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
print("\n長度不同的序列:")
for num, letter in zip(list1, list2):print(f"{num} - {letter}")# 創建字典
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
person = dict(zip(keys, values))
print(f"\n創建的字典: {person}")# 矩陣轉置
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(f"\n原矩陣: {matrix}")
print(f"轉置后: {list(transposed)}")
5. while循環
while循環在條件為真時重復執行代碼塊。
# 基本while循環
count = 0
print("倒計時:")
while count < 5:print(f"{5 - count}...")count += 1
print("發射!")# 用戶輸入循環
print("\n猜數字游戲:")
import random
target = random.randint(1, 100)
guess_count = 0
max_guesses = 7print(f"我想了一個1到100之間的數字,你有{max_guesses}次機會猜中它!")while guess_count < max_guesses:try:guess = int(input(f"第{guess_count + 1}次猜測,請輸入數字: "))guess_count += 1if guess == target:print(f"恭喜!你猜中了!數字是{target}")breakelif guess < target:print("太小了!")else:print("太大了!")if guess_count == max_guesses:print(f"游戲結束!正確答案是{target}")except ValueError:print("請輸入有效的數字!")# 無限循環(需要break退出)
print("\n簡單計算器(輸入'quit'退出):")
while True:user_input = input("請輸入表達式(如: 2+3)或'quit': ")if user_input.lower() == 'quit':print("再見!")breaktry:result = eval(user_input) # 注意:實際項目中不建議使用evalprint(f"結果: {result}")except:print("無效的表達式!")
循環控制(break, continue, pass)
1. break語句
break用于完全退出循環。
# 在for循環中使用break
print("查找第一個偶數:")
numbers = [1, 3, 5, 8, 9, 10, 11]
for num in numbers:if num % 2 == 0:print(f"找到第一個偶數: {num}")breakprint(f"{num}是奇數")# 在嵌套循環中使用break
print("\n在矩陣中查找特定值:")
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
found = Falsefor i, row in enumerate(matrix):for j, value in enumerate(row):if value == target:print(f"在位置({i}, {j})找到{target}")found = Truebreakif found:break# 使用標志變量的替代方案
def find_in_matrix(matrix, target):for i, row in enumerate(matrix):for j, value in enumerate(row):if value == target:return i, jreturn Noneposition = find_in_matrix(matrix, 8)
if position:print(f"數字8在位置{position}")
else:print("未找到數字8")
2. continue語句
continue用于跳過當前迭代,繼續下一次迭代。
# 跳過偶數,只打印奇數
print("只打印奇數:")
for i in range(1, 11):if i % 2 == 0:continue # 跳過偶數print(i, end=" ")
print()# 處理列表,跳過無效數據
data = [1, -2, 3, 0, -5, 6, 7, -8]
positive_sum = 0
print("\n處理數據(跳過負數和零):")
for num in data:if num <= 0:print(f"跳過: {num}")continuepositive_sum += numprint(f"累加: {num}, 當前和: {positive_sum}")print(f"正數總和: {positive_sum}")# 在while循環中使用continue
print("\n輸入驗證(跳過無效輸入):")
valid_inputs = []
count = 0while len(valid_inputs) < 3:count += 1user_input = input(f"請輸入第{count}個正整數: ")try:num = int(user_input)if num <= 0:print("請輸入正整數!")continuevalid_inputs.append(num)print(f"有效輸入: {num}")except ValueError:print("請輸入數字!")continueprint(f"收集到的有效輸入: {valid_inputs}")
3. pass語句
pass是一個空操作,用作占位符。
# 作為占位符
def future_function():pass # 暫時不實現,避免語法錯誤class FutureClass:pass # 暫時不實現# 在條件語句中使用
age = 25
if age < 18:pass # 暫時不處理未成年情況
elif age >= 65:print("享受老年優惠")
else:print("正常價格")# 在異常處理中使用
data = [1, 2, "invalid", 4, 5]
processed = []for item in data:try:result = int(item) * 2processed.append(result)except ValueError:pass # 忽略無效數據print(f"處理后的數據: {processed}")# 調試時的臨時代碼
def debug_function(x):if x < 0:pass # TODO: 處理負數情況return x * 2print(debug_function(5))
4. else子句在循環中的使用
Python的循環可以有else子句,當循環正常結束(沒有被break中斷)時執行。
# for循環的else子句
print("查找質數:")
def is_prime(n):if n < 2:return Falsefor i in range(2, int(n ** 0.5) + 1):if n % i == 0:print(f"{n}不是質數,因為{i} × {n//i} = {n}")return Falseelse:print(f"{n}是質數")return True# 測試
test_numbers = [17, 18, 19, 20]
for num in test_numbers:is_prime(num)print()# while循環的else子句
print("密碼驗證(最多3次機會):")
correct_password = "python123"
attempts = 0
max_attempts = 3while attempts < max_attempts:password = input(f"請輸入密碼(第{attempts + 1}次嘗試): ")attempts += 1if password == correct_password:print("密碼正確,登錄成功!")breakelse:print("密碼錯誤")
else:print("嘗試次數過多,賬戶被鎖定!")
推導式(Comprehensions)
推導式是Python的一個強大特性,可以用簡潔的語法創建列表、字典和集合。
1. 列表推導式
# 基本語法:[expression for item in iterable]
# 創建平方數列表
squares = [x**2 for x in range(1, 6)]
print(f"平方數: {squares}")# 等價的傳統寫法
squares_traditional = []
for x in range(1, 6):squares_traditional.append(x**2)
print(f"傳統寫法: {squares_traditional}")# 帶條件的列表推導式
# 語法:[expression for item in iterable if condition]
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"偶數的平方: {even_squares}")# 字符串處理
words = ["hello", "world", "python", "programming"]
uppercase_words = [word.upper() for word in words]
long_words = [word for word in words if len(word) > 5]
print(f"大寫單詞: {uppercase_words}")
print(f"長單詞: {long_words}")# 嵌套列表推導式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(f"展平矩陣: {flattened}")# 等價的傳統寫法
flattened_traditional = []
for row in matrix:for num in row:flattened_traditional.append(num)
print(f"傳統寫法: {flattened_traditional}")# 復雜的列表推導式
sentences = ["Hello World", "Python Programming", "Data Science"]
word_lengths = [[len(word) for word in sentence.split()] for sentence in sentences]
print(f"單詞長度: {word_lengths}")
2. 字典推導式
# 基本語法:{key_expr: value_expr for item in iterable}
# 創建平方數字典
squares_dict = {x: x**2 for x in range(1, 6)}
print(f"平方數字典: {squares_dict}")# 從兩個列表創建字典
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
people = {name: age for name, age in zip(names, ages)}
print(f"人員信息: {people}")# 帶條件的字典推導式
even_squares_dict = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(f"偶數平方字典: {even_squares_dict}")# 字符串處理
words = ["apple", "banana", "cherry", "date"]
word_lengths = {word: len(word) for word in words}
long_words_dict = {word: len(word) for word in words if len(word) > 5}
print(f"單詞長度: {word_lengths}")
print(f"長單詞: {long_words_dict}")# 轉換現有字典
original_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
# 鍵值互換
swapped_dict = {value: key for key, value in original_dict.items()}
print(f"鍵值互換: {swapped_dict}")# 過濾和轉換
filtered_dict = {key: value * 2 for key, value in original_dict.items() if value % 2 == 0}
print(f"偶數值翻倍: {filtered_dict}")
3. 集合推導式
# 基本語法:{expression for item in iterable}
# 創建平方數集合
squares_set = {x**2 for x in range(1, 6)}
print(f"平方數集合: {squares_set}")# 去重
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]
unique_numbers = {x for x in numbers}
print(f"去重后: {unique_numbers}")# 字符串去重
text = "hello world"
unique_chars = {char for char in text if char != ' '}
print(f"唯一字符: {unique_chars}")# 數學集合操作
set_a = {x for x in range(1, 11) if x % 2 == 0} # 偶數
set_b = {x for x in range(1, 11) if x % 3 == 0} # 3的倍數
print(f"偶數集合: {set_a}")
print(f"3的倍數集合: {set_b}")
print(f"交集: {set_a & set_b}")
print(f"并集: {set_a | set_b}")
4. 生成器表達式
生成器表達式類似列表推導式,但使用圓括號,返回生成器對象。
# 生成器表達式
squares_gen = (x**2 for x in range(1, 6))
print(f"生成器對象: {squares_gen}")
print(f"生成器類型: {type(squares_gen)}")# 遍歷生成器
print("生成器內容:")
for square in squares_gen:print(square, end=" ")
print()# 生成器只能遍歷一次
print("再次遍歷生成器:")
for square in squares_gen:print(square, end=" ") # 不會輸出任何內容
print("(空的,因為生成器已耗盡)")# 內存效率比較
import sys# 列表推導式(占用更多內存)
list_comp = [x**2 for x in range(1000)]
print(f"列表推導式內存: {sys.getsizeof(list_comp)} 字節")# 生成器表達式(占用很少內存)
gen_expr = (x**2 for x in range(1000))
print(f"生成器表達式內存: {sys.getsizeof(gen_expr)} 字節")# 實際應用:處理大文件
def process_large_file(filename):"""使用生成器處理大文件"""with open(filename, 'r') as file:# 生成器表達式,逐行處理,不會一次性加載整個文件processed_lines = (line.strip().upper() for line in file if line.strip())return processed_lines# 數學應用:無限序列
def fibonacci_gen():"""斐波那契數列生成器"""a, b = 0, 1while True:yield aa, b = b, a + b# 獲取前10個斐波那契數
fib_gen = fibonacci_gen()
first_10_fib = [next(fib_gen) for _ in range(10)]
print(f"前10個斐波那契數: {first_10_fib}")
實際應用示例
1. 數據處理
# 學生成績處理系統
students = [{"name": "張三", "scores": [85, 92, 78, 96]},{"name": "李四", "scores": [76, 88, 92, 84]},{"name": "王五", "scores": [95, 87, 91, 89]},{"name": "趙六", "scores": [68, 72, 75, 70]}
]print("學生成績分析:")
print("=" * 40)for student in students:name = student["name"]scores = student["scores"]# 計算平均分average = sum(scores) / len(scores)# 判斷等級if average >= 90:grade = "優秀"elif average >= 80:grade = "良好"elif average >= 70:grade = "中等"elif average >= 60:grade = "及格"else:grade = "不及格"print(f"{name}: 平均分 {average:.1f}, 等級 {grade}")# 找出最高分和最低分max_score = max(scores)min_score = min(scores)print(f" 最高分: {max_score}, 最低分: {min_score}")# 統計各分數段excellent = sum(1 for score in scores if score >= 90)good = sum(1 for score in scores if 80 <= score < 90)average_count = sum(1 for score in scores if 70 <= score < 80)poor = sum(1 for score in scores if score < 70)print(f" 分數分布 - 優秀:{excellent}, 良好:{good}, 中等:{average_count}, 較差:{poor}")print()# 班級統計
all_scores = [score for student in students for score in student["scores"]]
class_average = sum(all_scores) / len(all_scores)
print(f"班級平均分: {class_average:.1f}")# 找出班級最高分學生
best_student = max(students, key=lambda s: sum(s["scores"]) / len(s["scores"]))
print(f"班級第一名: {best_student['name']}")
2. 文本處理
# 文本分析工具
def analyze_text(text):"""分析文本的各種統計信息"""print(f"原文本: {text}")print("=" * 50)# 基本統計char_count = len(text)word_count = len(text.split())sentence_count = text.count('.') + text.count('!') + text.count('?')print(f"字符數: {char_count}")print(f"單詞數: {word_count}")print(f"句子數: {sentence_count}")# 字符頻率統計char_freq = {}for char in text.lower():if char.isalpha():char_freq[char] = char_freq.get(char, 0) + 1print("\n字符頻率(前5個):")sorted_chars = sorted(char_freq.items(), key=lambda x: x[1], reverse=True)for char, freq in sorted_chars[:5]:print(f" {char}: {freq}次")# 單詞頻率統計words = text.lower().split()word_freq = {}for word in words:# 去除標點符號clean_word = ''.join(char for char in word if char.isalnum())if clean_word:word_freq[clean_word] = word_freq.get(clean_word, 0) + 1print("\n單詞頻率(前5個):")sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)for word, freq in sorted_words[:5]:print(f" {word}: {freq}次")# 查找長單詞long_words = [word for word in words if len(word) > 6]print(f"\n長單詞(>6字符): {len(long_words)}個")if long_words:print(f" 示例: {', '.join(long_words[:3])}")# 測試文本分析
sample_text = """
Python is a powerful programming language.
It is easy to learn and has a simple syntax.
Python is widely used in data science, web development, and automation.
"""analyze_text(sample_text)
3. 游戲開發
# 簡單的猜數字游戲
import randomdef number_guessing_game():"""數字猜測游戲"""print("歡迎來到猜數字游戲!")print("我想了一個1到100之間的數字,請你來猜!")# 游戲設置target_number = random.randint(1, 100)max_attempts = 7attempts = 0guessed_numbers = []print(f"你有{max_attempts}次機會猜中這個數字。")print("輸入'hint'獲取提示,輸入'quit'退出游戲。")while attempts < max_attempts:# 顯示當前狀態remaining = max_attempts - attemptsprint(f"\n剩余機會: {remaining}")if guessed_numbers:print(f"已猜過的數字: {sorted(guessed_numbers)}")# 獲取用戶輸入user_input = input("請輸入你的猜測: ").strip().lower()# 處理特殊命令if user_input == 'quit':print(f"游戲結束!正確答案是 {target_number}")returnelif user_input == 'hint':# 提供提示if target_number % 2 == 0:print("提示: 這是一個偶數")else:print("提示: 這是一個奇數")continue# 驗證輸入try:guess = int(user_input)except ValueError:print("請輸入有效的數字!")continueif guess < 1 or guess > 100:print("請輸入1到100之間的數字!")continueif guess in guessed_numbers:print("你已經猜過這個數字了!")continue# 處理猜測attempts += 1guessed_numbers.append(guess)if guess == target_number:print(f"\n🎉 恭喜你!猜中了!")print(f"正確答案是 {target_number}")print(f"你用了 {attempts} 次機會")# 評價表現if attempts <= 3:print("太厲害了!你是猜數字高手!")elif attempts <= 5:print("不錯的表現!")else:print("終于猜中了!")returnelif guess < target_number:print("太小了!試試更大的數字")# 給出范圍提示larger_guesses = [n for n in guessed_numbers if n < target_number]if larger_guesses:min_range = max(larger_guesses) + 1print(f"提示: 答案在 {min_range} 到 100 之間")else:print("太大了!試試更小的數字")# 給出范圍提示smaller_guesses = [n for n in guessed_numbers if n > target_number]if smaller_guesses:max_range = min(smaller_guesses) - 1print(f"提示: 答案在 1 到 {max_range} 之間")# 游戲失敗print(f"\n😞 很遺憾,你沒有在{max_attempts}次機會內猜中!")print(f"正確答案是 {target_number}")print("再試一次吧!")# 運行游戲
# number_guessing_game()
性能優化技巧
import time# 1. 列表推導式 vs 傳統循環
def compare_list_creation():"""比較不同創建列表的方法的性能"""n = 100000# 方法1:傳統for循環start = time.time()result1 = []for i in range(n):if i % 2 == 0:result1.append(i * 2)time1 = time.time() - start# 方法2:列表推導式start = time.time()result2 = [i * 2 for i in range(n) if i % 2 == 0]time2 = time.time() - start# 方法3:filter + mapstart = time.time()result3 = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, range(n))))time3 = time.time() - startprint(f"傳統循環: {time1:.4f}秒")print(f"列表推導式: {time2:.4f}秒")print(f"filter+map: {time3:.4f}秒")print(f"列表推導式比傳統循環快 {time1/time2:.1f} 倍")# 2. 成員檢測:list vs set
def compare_membership_test():"""比較列表和集合的成員檢測性能"""data = list(range(10000))data_set = set(data)search_items = [1000, 5000, 9999]# 列表查找start = time.time()for item in search_items * 1000: # 重復1000次result = item in datalist_time = time.time() - start# 集合查找start = time.time()for item in search_items * 1000: # 重復1000次result = item in data_setset_time = time.time() - startprint(f"列表查找: {list_time:.4f}秒")print(f"集合查找: {set_time:.4f}秒")print(f"集合比列表快 {list_time/set_time:.1f} 倍")print("性能比較:")
print("=" * 30)
compare_list_creation()
print()
compare_membership_test()
總結
本章詳細介紹了Python的控制結構:
- 條件語句: if、elif、else,用于程序分支
- 循環語句: for和while,用于重復執行代碼
- 循環控制: break、continue、pass,用于控制循環流程
- 推導式: 列表、字典、集合推導式,提供簡潔的數據處理方式
控制結構使用指南:
┌─────────────────────────────────────────────┐
│ 何時使用哪種控制結構 │
├─────────────────────────────────────────────┤
│ if語句: │
│ ? 根據條件執行不同代碼 │
│ ? 數據驗證和錯誤處理 │
│ │
│ for循環: │
│ ? 遍歷已知序列 │
│ ? 執行固定次數的操作 │
│ │
│ while循環: │
│ ? 條件未知時的重復執行 │
│ ? 用戶交互和事件處理 │
│ │
│ 推導式: │
│ ? 簡潔的數據轉換 │
│ ? 過濾和映射操作 │
│ ? 性能要求較高的場景 │
└─────────────────────────────────────────────┘
掌握這些控制結構是編寫高效Python程序的基礎,它們讓程序能夠處理復雜的邏輯和數據操作。
下一章預告: 函數與模塊 - 學習如何定義函數、參數傳遞、作用域和模塊化編程。