Xử lý lỗi StopIteration
Lớp Playlist từ bài trước đã được cập nhật để in ra thông báo bao gồm bài hát hiện đang phát, như bên dưới. Với iterator tùy chỉnh này, bạn sẽ luyện cách xử lý ngoại lệ StopIteration một cách gọn gàng. Chúc bạn học tốt!
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
Bài tập này là một phần của khóa học
Lập trình Hướng đối tượng Nâng cao với Python
Hướng dẫn bài tập
- Tạo một
Playlisttên làclassic_rock_playlisttừ các tiêu đề trong danh sáchsongs; đảm bảoclassic_rock_playlistphát xáo trộn các bài hát. - Dùng khối
try-exceptbên trong vòng lặpwhileđể phát bài tiếp theo trongclassic_rock_playlist. - Cập nhật logic
try-exceptđể xử lý lỗiStopIteration, in ra một thông báo và thoát khỏi vòng lặp.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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!")
____