Python 中的控制流程

Python 中的控制流程

本文將解釋 Python 中的控制流程。

YouTube Video

Python 中的 If 語句

Python 中的 if 語句是用於條件分支的語法。如果特定條件的結果為 True(真),它將執行一段代碼區塊。

基本語法

Python 中的 if 語句基本遵循以下結構。

1x = 10
2
3if x > 5: # Check if the condition(x > 5) is True
4    # If the condition is True, execute this code block
5    print("x is greater than 5")

在此範例中,若變數 x 大於 5,則會輸出 "x 大於 5"

else 語句

if 語句之後使用 else,可以指定當條件為假時執行的代碼。

1x = 3
2
3if x > 5:
4    print("x is greater than 5")
5else:
6    print("x is less than or equal to 5")

在此範例中,輸出將會是 "x 小於或等於 5"

elif 語句

如果需要檢查多個條件,可以使用 elif,它是 "else if" 的縮寫。

1x = 5
2
3if x > 5:
4    print("x is greater than 5")
5elif x == 5:
6    print("x is equal to 5")
7else:
8    print("x is less than 5")

在此範例中,會輸出 "x 等於 5"

注意事項

  • ifelifelse 之後需要使用冒號 (:)。
  • 當條件為真時執行的代碼區塊需要進行縮排。在 Python 中,標準縮排通常是 4 個空格,但只要保持一致,使用其他數量的空格也可以。
  • 您可以使用任何結果為布林值的表達式作為條件。這意味著您可以使用結合比較或邏輯運算符的條件表達式。

掌握 Python 的 if 語句可以讓您靈活地控制程式的執行流程。

在 Python 中進行多條件分支

在 Python 中有多種方法可以實現類似其他語言中 switch 功能的機制。在 Python 中,常用 if-elif-else 語句或字典來創建類似於 switch 語句的結構。

方法一:if-elif-else 語句

最簡單的方法是使用 if-elif-else 語句進行條件分支。

 1def switch_example(value):
 2    if value == 1:
 3        return "Value is one"
 4    elif value == 2:
 5        return "Value is two"
 6    elif value == 3:
 7        return "Value is three"
 8    else:
 9        return "Unknown value"
10
11print(switch_example(1))  # Output: Value is one
12print(switch_example(4))  # Output: Unknown value

方法二:使用字典

透過將函數或值映射到字典,可以創建類似於 switch 語句的結構。當需要對特定值執行不同操作時,這種方法非常方便。

 1def case_one():
 2    return "Value is one"
 3
 4def case_two():
 5    return "Value is two"
 6
 7def case_default():
 8    return "Unknown value"
 9
10def switch_example(value):
11    switch_dict = {
12        1: case_one,
13        2: case_two
14    }
15
16    # Use get() method to retrieve the corresponding function from the dictionary
17    # If the value is not found in the dictionary, use case_default as a fallback
18    return switch_dict.get(value, case_default)()
19
20print(switch_example(1))  # Output: Value is one
21print(switch_example(3))  # Output: Unknown value

方法三:match 語句 (適用於 Python 3.10 及以上版本)

match 語句是在 Python 3.10 中引入的。這是一種模式匹配語法,提供了類似於 switch 語句的功能。

 1def switch_example(value):
 2    match value:
 3        case 1:
 4            return "Value is one"
 5        case 2:
 6            return "Value is two"
 7        case 3:
 8            return "Value is three"
 9        case _:
10            return "Unknown value"
11
12print(switch_example(1))  # Output: Value is one
13print(switch_example(4))  # Output: Unknown value

總結

  • if-elif-else 語句:簡單且適用於多種情況。
  • 字典:使用函數或值的映射來實現高效分支。
  • match 語句:在 Python 3.10 及以上版本中提供更直觀的分支方式。最接近於 switch 語句。

Python 中的 For 迴圈

Python 的 for 語句用於遍歷像是列表、字串或字典等可迭代對象中的每個元素。for 語句的基本語法如下:。

1# Loop through each item in the iterable
2for variable in iterable:
3    # Execute this block of code for each item in the iterable
4    code_to_execute

以下是一些具體範例:。

使用列表的範例

1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3    print(fruit)

此程式碼調用 print 函數來輸出列表 fruits 中每個元素的名稱。

使用 range() 的範例

range() 函數生成指定範圍內的整數,非常適合用於數位迭代。

1for i in range(5):
2    print(i)

range(5) 生成從 0 到 4 的整數。在此範例中,將依序輸出 0, 1, 2, 3, 4

使用字典的範例

在使用字典時,預設情況下會迭代鍵,但也可以檢索鍵值對。

1person = {"name": "Alice", "age": 25}
2for key in person:
3    print(key, person[key])

或者,使用 items() 方法同時檢索鍵和值。

1person = {"name": "Alice", "age": 25}
2for key, value in person.items():
3    print(key, value)

巢狀的 for 迴圈

也可以巢狀使用 for 迴圈來執行複雜的迭代過程。

1matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2for row in matrix:
3    for num in row:
4        print(num)

此程式碼遍歷列表 matrix 的每一行,並依次輸出每一行中的數字。

continue 用於跳過某次迭代,而 break 用於終止迴圈

for 迴圈中使用 continue 會跳過當前的迭代並進入下一次迭代。另外,使用 break 將完全終止迴圈。

1for i in range(10):
2    if i == 5:
3        continue
4    if i == 8:
5        break
6    print(i)

在此範例中,當 i 等於 5 時迴圈會跳過,當 i 等於 8 時迴圈將終止。因此,輸出將是 0, 1, 2, 3, 4, 6, 7

Python 的 for 迴圈非常靈活,可以用於各種情境。根據您要執行的迭代處理類型,可以將其與列表、字典、字串以及 range() 結合使用。

Python 中的 while 迴圈

在 Python 中,while 迴圈是一種控制結構,用於在條件為 True 時反覆執行區塊內的程式碼。while 迴圈的基本語法如下:。

1while condition:
2    # This block of code will be executed repeatedly as long as the condition is true
3    statement1
4    statement2
5    ...

範例:

在以下範例中,使用 while 迴圈輸出從 1 到 5 的數字。

1i = 1
2while i <= 5:
3    print(i)
4    i += 1

此代碼的運作方式如下。

  • i 為 1 開始,每當 i 小於等於 5 時列印 i,並將 i 每次加 1。

注意:

使用 while 語句時,您需要注意以下幾點。

  1. 小心無限迴圈

    • 如果 while 迴圈中的條件永遠為真,將導致無限迴圈。必須執行適當的操作以改變條件,否則程式將無法停止。
  2. 使用 breakcontinue

    • 當您想要提前結束迴圈時可使用 break
    • continue 會跳過目前這次的迭代,直接開始下一次。請小心,不正確的迴圈條件可能會導致無限迴圈。

break 的範例:

1i = 1
2while i <= 5:
3    if i == 3:
4        break  # Exit the loop when i becomes 3
5    print(i)
6    i += 1
  • 在此情況下,輸出 12 後,當 i 等於 3 時迴圈結束。

continue 的範例:

1i = 0
2while i < 5:
3    i += 1
4    if i == 3:
5        # Skip the print statement and move to the next loop iteration when i is 3
6        continue
7    print(i)
  • 在此情況下,僅跳過輸出 3,最終結果為 1, 2, 4, 5
  • 在迴圈開頭增加 i 的值,即使執行了 continue,計數器仍會遞增,從而防止無限迴圈。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video