Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ forループにおけるelse文 | Forループ
Pythonループチュートリアル

bookforループにおけるelse文

メニューを表示するにはスワイプしてください

Pythonでは、else文をforループと組み合わせて使用可能。elseブロックは、ループがbreak文で中断されずにすべての反復処理を完了した場合に実行される。この機能は、ループが最後まで実行されたことを確認する際に特に有用。

この概念をtravel_listに適用。各目的地を出力し、すべての目的地が中断なく処理された場合、elseブロックで完了を確認。

1234567
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Printing all destinations for city in travel_list: print(city) else: print('All destinations have been listed.')
copy

次に、breakを使ってループを途中で終了する条件を追加。特定の都市(例:'Barcelona')を探して見つけた場合、ループは停止し、elseブロックは実行されない。

123456789
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Searching for a specific city for city in travel_list: print(city) if city == 'Barcelona': break else: print('All destinations have been listed.')
copy

この場合、else によってループが中断されたため、break ブロックは実行されません。not in を使用して、都市がリストに存在しないことを確認できます。リストに都市が見つからない場合、特定の処理を実行できます。

123456789
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Checking if a city is NOT in the list search_city = 'Paris' if search_city not in travel_list: print(search_city, 'is not in the travel list.') else: print(search_city, 'is in the travel list.')
copy

not in 演算子は、要素がコレクション(リスト、タプル、または文字列など)に存在しないかどうかを確認するためのもの。favorite_city リストに都市が含まれていないかどうかを確認する際に使用。

question mark

Python の else ループにおける for ブロックの役割は何か。

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  5
some-alt