1. Learn
  2. /
  3. Courses
  4. /
  5. Intermediate Object-Oriented Programming in Python

Connected

Exercise

Handling a StopIteration error

The Playlist class from the previous exercise has been updated to print a message including a current song being played, and is shown below. Using this custom iterator, you'll practice handling a StopIteration exception gracefully. Enjoy!

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

Instructions

100 XP
  • Create a Playlist called classic_rock_playlist made up of the titles in the songs list; make sure classic_rock_playlist shuffles songs.
  • Using a try-except block within a while loop, play the next song in classic_rock_playlist.
  • Update the try-except logic to handle a StopIteration error, printing a message, and breaking from the loop.