開始使用免費開始

處理 StopIteration 錯誤

上一個練習中的 Playlist 類別已更新,現在會在播放時印出目前歌曲的訊息,程式碼如下。使用這個自訂迭代器,你將練習優雅地處理 StopIteration 例外。試試看吧!

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

本練習屬於課程

Python 物件導向程式設計進階

檢視課程

練習說明

  • 建立名為 classic_rock_playlistPlaylist,其內容由 songs 清單中的標題組成;記得讓 classic_rock_playlist 隨機播放歌曲(shuffle)。
  • while 迴圈中使用 try-except 區塊,播放 classic_rock_playlist 的下一首歌。
  • 更新 try-except 邏輯以處理 StopIteration 錯誤:印出一則訊息,然後跳出迴圈。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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!")
		____
編輯並執行程式碼