2026.07.04(土) / 16:20

for … else

最終更新
2026.07.04
タグ

for_else.py

def find_apple(fruits):
    for fruit in fruits:
        if fruit == "apple":
            print("Found an apple!")
            break
    else:
        print("No apple found.")

fruits_a = ["apple", "banana", "cherry"]
fruits_b = ["banana", "cherry"]

find_apple(fruits_a)
find_apple(fruits_b)

find_apple関数

果物のリストが渡ってくる

果物がappleなら、「Found an apple!」→ 処理終了

それ以外の場合、「No apple found.」

appleが見つかったら、breakでfor文を抜ける

この記事がよかったら、いいねで応援してください。