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
Este exercício faz parte do curso
Intermediate Object-Oriented Programming in Python
Instruções do exercício
- Create a
Playlistcalledclassic_rock_playlistmade up of the titles in thesongslist; make sureclassic_rock_playlistshuffles songs. - Using a
try-exceptblock within awhileloop, play the next song inclassic_rock_playlist. - Update the
try-exceptlogic to handle aStopIterationerror, printing a message, and breaking from the loop.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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!")
____