Get startedGet started for free

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

This exercise is part of the course

Intermediate Object-Oriented Programming in Python

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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!")
		____
Edit and Run Code