BaşlayınÜcretsiz Başlayın

StopIteration hatasını ele alma

Önceki egzersizdeki Playlist sınıfı, çalınan güncel şarkıyı içeren bir mesaj yazdıracak şekilde güncellendi ve aşağıda gösteriliyor. Bu özel yineleyiciyi kullanarak, bir StopIteration istisnasını zarifçe ele almayı pratik yapacaksın. Keyfini çıkar!

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

Bu egzersiz

Python'da Orta Düzey Nesne Yönelimli Programlama

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • songs listesindeki başlıklardan oluşan classic_rock_playlist adında bir Playlist oluştur; classic_rock_playlist şarkıları karıştırsın.
  • Bir while döngüsü içinde try-except bloğu kullanarak classic_rock_playlist içinde bir sonraki şarkıyı çal.
  • StopIteration hatasını ele alacak şekilde try-except mantığını güncelle, bir mesaj yazdır ve döngüden çık.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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!")
		____
Kodu Düzenle ve Çalıştır