在寫程式時,我們不只需要存資料、做計算,還要能根據不同情況做出「選擇」與「重複執行」。這一章的主角就是 條件判斷 與 流程控制。
想像你在日常生活中:
這些邏輯結構,讓程式能根據情況自動做決策或反覆執行工作。掌握這一章的內容,你就能讓程式「會思考、會重複」,不再只是單純的一行一行往下跑。
age = 18
if age >= 18:
print("成年人")
else:
print("未成年人")
score = 85
if score >= 90:
print("優等")
elif score >= 80:
print("甲等")
elif score >= 70:
print("乙等")
elif score >= 60:
print("丙等")
else:
print("不及格")
age = 25
has_license = True
# and: 兩個條件都要成立
if age >= 18 and has_license:
print("可以開車")
# or: 其中一個條件成立即可
weather = "sunny"
if weather == "sunny" or weather == "cloudy":
print("適合出門")
# not: 條件相反
is_raining = False
if not is_raining:
print("不用帶傘")
=
和比較 ==
#錯誤寫法,執行會報錯
x = 5
if x = 5:
print("YES")
# 正確寫法如下:
if x == 5: # 比較是否相等
print("YES")
# 其他比較運算子
if x != 5: # 不等於
print("不是5")
if x > 3: # 大於
print("大於3")
-- 若把上面程式碼複製貼上,執行後會報錯,因等號要輸入雙等號才會是正確的。
-- 後續把第一行的錯誤程式碼註解後,再執行才會是正確的結果如下:
Python 用縮排來表示程式碼的層級關係,通常使用 4 個空格。
# 錯誤:沒有縮排
if True:
print("YES")
# 正確:有縮排
if True:
print("YES") # 縮排 4 個空格
# 巢狀結構
if True:
print("外層")
if True:
print("內層") # 縮排 8 個空格
-- 以下範例是沒有縮排,導致執行後會報錯
--後續只要縮排就會顯示正確的結果,如下所示:
# 傳統寫法
age = 25
if age >= 18:
status = "成年"
else:
status = "未成年"
# 簡化寫法(條件表達式)
status = "成年" if age >= 18 else "未成年"
print(status)
-- 雖上面兩種寫法都可以執行,並結果相同,但第二種條件表達式閱讀上較乾淨。
count = 0
while count < 5:
print(f"第 {count + 1} 次執行")
count += 1
print("迴圈結束")
-- 可以使用以下網頁,使迴圈視覺化,能夠讀懂程式如何運行的。
https://pythontutor.com/python-compiler.html#mode=edit
count < 5
是否為 True# 無窮迴圈 ,若不小心執行了請輸入 control + c
x = 0
while x < 5:
print(x)
# 忘記寫 x += 1,x 永遠是 0
# 正確寫法
x = 0
while x < 5:
print(x)
x += 1 # 記得更新條件變數
# break 範例:找到目標就跳出
numbers = [1, 3, 7, 2, 9, 4]
target = 7
i = 0
while i < len(numbers):
if numbers[i] == target:
print(f"找到目標 {target} 在位置 {i}")
break # 立刻跳出整個迴圈
i += 1
# continue 範例:跳過偶數,只印奇數
n = 0
while n < 10:
n += 1
if n % 2 == 0: # 如果是偶數
continue # 跳過這次,不執行下面的 print
print(f"{n} 是奇數")
while True:
password = input("請輸入密碼 (輸入 'quit' 結束): ")
if password == "quit":
print("程式結束")
break
elif password == "123456":
print("密碼正確!歡迎進入系統")
break
else:
print("密碼錯誤,請重新輸入")
# 計算 1 到 100 的總和
total = 0
num = 1
while num <= 100:
total += num
num += 1
print(f"1到100的總和是: {total}")
for
迴圈常用於「重複處理一組已知的資料」,例如數字序列、字串、list、dict 等。它的特點是:次數通常可以事先確定,不像 while
迴圈需要靠條件判斷才知道何時結束。
range()
是最常搭配 for
使用的函式,可以產生一系列整數。
# range(stop): 從 0 開始到 4 ,因為stop-1
for i in range(5):
print(i) # 輸出: 0, 1, 2, 3, 4
# range(start, stop): 從 start 到 stop-1
for i in range(2, 7):
print(i) # 輸出: 2, 3, 4, 5, 6
# range(start(), stop(到多少), step(間隔)): 指定間隔
for i in range(0, 10, 2):
print(i) # 輸出: 0, 2, 4, 6, 8
# 倒數計數
for i in range(5, 0, -1):
print(i) # 輸出: 5, 4, 3, 2, 1
range()
本身不是 list,而是一個可迭代物件,需要時可用 list(range(5))
轉換for
迴圈不只能搭配 range()
,還能直接對容器進行逐一取出。
# 遍歷 list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"我喜歡吃 {fruit}")
# 遍歷字串
for char in "Python":
print(char) # P, y, t, h, o, n
# 遍歷 dict
student = {"name": "Jr", "age": 25, "score": 99}
for key in student:
print(f"{key}: {student[key]}")
# 同時取得 key 和 value
for key, value in student.items():
print(f"{key}: {value}")
.items()
同時取得 key 與 valuefor
裡面還能再放一個 for
,這就是巢狀迴圈。
print("九九乘法表:")
for i in range(1, 10):
for j in range(1, 10):
result = i * j
print(f"{i}×{j}={result:2d}", end=" ")
print() # 換行
end=" "
讓輸出在同一行顯示列表生成式是 for
迴圈的簡化版,可以快速建立新的 list。
# 傳統寫法:建立平方數列表
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # [1, 4, 9, 16, 25]
# 列表生成式:更簡潔
squares = [i ** 2 for i in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# 帶條件的列表生成式:只要偶數的平方
even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
[運算 for 變數 in 可迭代物件 if 條件]
for
,程式更易讀日常生活中,for
迴圈就像「逐一點名」或「一張張翻相簿」,確保每個項目都被處理到。