Gestire un errore StopIteration
La classe Playlist dell'esercizio precedente è stata aggiornata per stampare un messaggio con il brano attualmente in riproduzione, ed è mostrata qui sotto. Usando questo iteratore personalizzato, farai pratica nel gestire con eleganza un'eccezione StopIteration. Divertiti!
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
Questo esercizio fa parte del corso
Programmazione a oggetti intermedia in Python
Istruzioni dell'esercizio
- Crea una
Playlistchiamataclassic_rock_playlistcomposta dai titoli nella listasongs; assicurati checlassic_rock_playlistmescoli i brani. - Usando un blocco
try-exceptall'interno di un ciclowhile, riproduci il brano successivo inclassic_rock_playlist. - Aggiorna la logica
try-exceptper gestire un erroreStopIteration, stampando un messaggio ed uscendo dal ciclo conbreak.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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!")
____