2026.07.04(土) / 16:20
for … else
- ID
- 38959
- Published
- 2026-07-04 16:20
- Modified
- 2026-07-04 16:32
- Author
- khiro
- Categories
- デフォルト
- Tags
- Python
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文を抜ける