始める無料で始める

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!")
		____
コードを編集して実行