第3章 控制流程

在程序中,控制流程(Control Flow)決定了代碼按什麼順序執行。掌握條件判斷與循環,可以讓你的程序根據不同情況執行不同的分支,並對數據進行高效處理。

本系列文章所使用到的示例源碼:Python從入門到精通示例代碼

3.1 條件語句(if、elif、else)

3.1.1 基本概念與語法

條件語句用於根據布爾條件(True/False)選擇性地執行代碼塊。

  • 單分支(if)
age = 20
if age >= 18:
    print("已成年")

輸出:

已成年
  • 雙分支(if-else)
score = 59
if score >= 60:
    print("及格")
else:
    print("不及格")

輸出:

不及格
  • 多分支(if-elif-else)
score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
else:
    print("D")

輸出:

B

3.1.2 布爾與比較/邏輯運算

  • 布爾值:TrueFalse
  • 比較運算:==!=<<=>>=
  • 邏輯運算:andornot
x = 3
print(x > 2, x == 5)

n = 7
print(n > 0 and n % 2 == 1)

輸出:

True False
True

3.1.3 嵌套條件語句

user = "admin"
pwd = "123"

if user == "admin":
    if pwd == "123":
        print("登錄成功")
    else:
        print("密碼錯誤")
else:
    print("用戶不存在")

輸出:

登錄成功

3.1.4 條件表達式(三元運算符)

age = 20
status = "成年" if age >= 18 else "未成年"
print(status)

輸出:

成年

3.1.5 實際應用:閏年判斷

規則:閏年滿足 (被4整除且不被100整除) 或 被400整除

year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print("閏年")
else:
    print("平年")

輸出:

閏年

3.2 循環語句(for、while)

3.2.1 基本概念

循環用於重複執行代碼塊,直到條件不滿足或顯式中斷。

3.2.2 while 循環

i = 1
while i <= 3:
    print(i)
    i += 1

輸出:

1
2
3

避免無限循環:確保循環條件會變爲 False,必要時在循環體內更新變量。

while-else:循環未被 break 打斷時執行 else

i = 1
while i < 3:
    print(i)
    i += 1
else:
    print("循環正常結束")

輸出:

1
2
循環正常結束

3.2.3 for 循環與遍歷

遍歷序列(字符串、列表、元組等):

for c in "hi":
    print(c)

for item in [1, 2, 3]:
    print(item)

輸出:

h
i
1
2
3

range() 的使用:

for i in range(3):
    print(i)

for i in range(1, 4):
    print(i)

for i in range(2, 7, 2):
    print(i)

輸出(截取要點):

0
1
2
1
2
3
2
4
6

for-else:無 break 時執行 else

for i in range(3):
    print(i)
else:
    print("無break,執行else")

輸出:

0
1
2
無break執行else

3.2.4 循環選擇策略

  • 數據量小且次數明確優先用 for;基於條件循環優先用 while
  • 需要下標且遍歷序列時,配合 enumerate
  • 需要計數可用 range(n),需要區間用 range(start, stop[, step])

3.3 break 和 continue 語句

3.3.1 break 的作用與用法

立即結束所在層的循環。

在 while 中:

i = 0
while True:
    i += 1
    if i == 3:
        break
print(i)

輸出:

3

在 for 中:

for n in [1, 3, 5, 8, 9]:
    if n % 2 == 0:
        print("找到偶數:", n)
        break

輸出:

找到偶數: 8

多層循環中的 break(只跳出內層):

for i in range(1, 4):
    for j in range(1, 4):
        if j == 2:
            break
        print(i, j)

輸出(截取要點):

1 1
2 1
3 1

3.3.2 continue 的作用與用法

跳過當前迭代,直接進入下一輪。

for n in range(1, 6):
    if n % 2 == 0:
        continue
    print(n)

輸出:

1
3
5

3.3.3 區別與最佳實踐

  • break 結束循環;continue 跳過本次迭代。
  • 避免與過深的嵌套混用,必要時抽函數或使用標誌位/any/all
  • 查找目標時,優先考慮 any() 並結合生成式提高可讀性。

3.4 pass 語句

3.4.1 概念

pass 表示“什麼都不做”,常用於佔位,保持語法完整。

3.4.2 使用場景

  • 在函數/類/條件中佔位,後續再補充實現。
def todo():
    pass

class Empty:
    pass

flag = False
if flag:
    pass
else:
    print("else執行")

輸出:

else執行

3.4.3 與其他語句的區別

  • pass 不改變流程;break/continue 改變循環執行。

3.5 循環嵌套與實踐

3.5.1 打印圖案

n = 5
for i in range(1, n + 1):
    print("*" * i)

輸出(截取要點):

*
**
***
****
*****

3.5.2 二維數據處理與求和

matrix = [[1, 2, 3], [4, 5, 6]]
total = 0
for row in matrix:
    for num in row:
        total += num
print(total)

輸出:

21

3.5.3 查找算法(帶提前結束)

matrix = [[1, 2, 3], [4, 5, 6]]
target = 5
found = False

for row in matrix:
    for num in row:
        if num == target:
            found = True
            break
    if found:
        break

print("找到" if found else "未找到")

輸出:

找到

利用內置函數提升可讀性:

nums = [1, 3, 5, 8]
print(any(n % 2 == 0 for n in nums))

輸出:

True

3.5.4 性能與優化建議

  • 多重循環通常是 \(O(n^2)\) 或更高,優先考慮提前 break、剪枝條件。
  • 善用內置函數(anyallsummaxmin)與生成式提升可讀性與速度。
  • 遍歷時如需下標,用 enumerate;需要鍵值對,用 items()
  • 複雜邏輯抽函數,減少嵌套層級。

3.5.5 實際小案例:過濾有效郵箱

emails = ["a@b.com", "bad", "c@d.com"]
valid = []
for e in emails:
    if "@" not in e:
        continue
    valid.append(e)
print(valid)

輸出:

['a@b.com', 'c@d.com']

通過本章的學習,你應能熟練使用條件判斷與循環,在實際項目中寫出更清晰、可靠且高效的控制流程代碼。

小夜