Een StopIteration-fout afhandelen
De Playlist-klasse uit de vorige oefening is bijgewerkt om een bericht te printen met het huidige nummer dat wordt afgespeeld, en staat hieronder. Met deze aangepaste iterator ga je oefenen met het netjes afhandelen van een StopIteration-exceptie. Veel plezier!
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
Deze oefening maakt deel uit van de cursus
Gevorderde objectgeoriënteerde programmering in Python
Oefeninstructies
- Maak een
Playlistmet de naamclassic_rock_playlistop basis van de titels in de lijstsongs; zorg ervoor datclassic_rock_playlistde nummers schudt. - Gebruik binnen een
while-lus eentry-except-blok om het volgende nummer inclassic_rock_playlistaf te spelen. - Werk de
try-except-logica bij om eenStopIteration-fout af te handelen: print een bericht en breek uit de lus.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# 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!")
____