开始使用免费开始使用

处理 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 会打乱歌曲顺序。
  • 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!")
		____
编辑并运行代码