退出 Python 中的多重迴圈
    
    Muhammad Maisam Abbas
    2023年12月11日
    
    Python
    Python Loop
    
 
在本教程中,我們將討論退出 Python 中多個迴圈的方法。
在 Python 中使用 return 語句打破多個迴圈
    
在這種方法中,我們可以在使用者定義的函式內編寫巢狀迴圈,並使用 return 語句退出巢狀迴圈。以下程式碼示例向我們展示瞭如何使用 return 語句打破 Python 的多個迴圈。
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def search(n):
    for x in range(3):
        for y in range(3):
            if list1[x][y] == n:
                return "Found"
    return "Not Found"
result = search(10)
print(result)
輸出:
Found
在上面的程式碼中,我們首先初始化 2D 列表並定義一個函式 search(n),該函式使用巢狀迴圈在 list1 中搜尋特定值。return 語句用於退出巢狀迴圈。如果在列表中找到該值,函式 search(n) 將返回 Found,如果在列表中未找到該值,則將返回 Not Found。
在 Python 中使用 break 關鍵字退出多重迴圈
    
我們還可以使用 for/else 迴圈退出巢狀迴圈。else 子句在成功完成 for 之後執行。如果 for 迴圈中斷,則不執行 else。以下程式碼示例向我們展示瞭如何使用 for/else 迴圈在 Python 中產生多個迴圈。
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = 6
for x in range(3):
    for y in range(3):
        if list1[x][y] == n:
            print("Found")
            break
    else:
        continue
    break
輸出:
Found
在上面的程式碼中,我們首先初始化 2D 列表並執行巢狀迴圈以在 list1 中搜尋特定值。外迴圈只是一個簡單的 for 迴圈。內部的 for 迴圈帶有 else 子句。如果找到該值,則程式碼會退出巢狀迴圈,如果找不到該值,則繼續進行直到完成。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn