CommencerCommencer gratuitement

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

Cet exercice fait partie du cours

Intermediate Object-Oriented Programming in Python

Afficher le cours

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.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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!")
		____
Modifier et exécuter le code