ComeçarComece de graça

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

Ver curso

Instruções do exercício

  • Crie uma Playlist chamada classic_rock_playlist composta pelos títulos da lista songs; garanta que classic_rock_playlist embaralhe as músicas.
  • Usando um bloco try-except dentro de um loop while, reproduza a próxima música em classic_rock_playlist.
  • Atualize a lógica de try-except para tratar um erro StopIteration, imprimindo uma mensagem e saindo do loop com break.

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!")
		____
Editar e executar o código