StopIteration エラーの処理
前の演習の Playlist クラスに、現在再生中の曲名を含むメッセージを表示するように更新を加えました。以下に示すこのカスタムイテレータを使って、StopIteration 例外を丁寧に処理する練習をします。楽しんでください!
class Playlist:
def __init__(self, songs, shuffle=False):
self.songs = songs
self.index = 0
if shuffle:
random.shuffle(self.songs)
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.songs):
raise StopIteration
print(f"Playing {self.songs[self.index]}")
self.index += 1
この演習はコースの一部です
Python 中級オブジェクト指向プログラミング
演習の手順
songsリストのタイトルで構成されたclassic_rock_playlistというPlaylistを作成し、曲をシャッフルするようにしてください。whileループ内でtry-exceptブロックを使い、classic_rock_playlistの次の曲を再生してください。StopIterationエラーを処理できるようにtry-exceptのロジックを更新し、メッセージを表示してからループを終了してください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Create a classic rock playlist using the songs list
songs = ["Hooked on a Feeling", "Yesterday", "Mr. Blue Sky"]
____ = ____(____, ____=True)
while True:
____:
# Play the next song in the playlist
next(____)
# If there is a StopIteration error, print a message and
# stop the playlist
____ ____:
____("Reached end of playlist!")
____