Tratando um erro StopIteration
A classe Playlist do exercício anterior foi atualizada para imprimir uma mensagem com a música atual sendo reproduzida e está mostrada abaixo. Usando esse iterador personalizado, você vai praticar como tratar uma exceção StopIteration de forma elegante. Divirta-se!
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
Programação Orientada a Objetos Intermediária em Python
Instruções do exercício
- Crie uma
Playlistchamadaclassic_rock_playlistcomposta pelos títulos da listasongs; garanta queclassic_rock_playlistembaralhe as músicas. - Usando um bloco
try-exceptdentro de um loopwhile, reproduza a próxima música emclassic_rock_playlist. - Atualize a lógica de
try-exceptpara tratar um erroStopIteration, imprimindo uma mensagem e saindo do loop combreak.
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!")
____