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
Exercise instructions
- Create a
Playlist
calledclassic_rock_playlist
made up of the titles in thesongs
list; make sureclassic_rock_playlist
shuffles songs. - Using a
try
-except
block within awhile
loop, play the next song inclassic_rock_playlist
. - Update the
try
-except
logic to handle aStopIteration
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!")
____