การจัดการข้อผิดพลาด StopIteration
คลาส Playlist จากแบบฝึกหัดก่อนหน้าได้รับการอัปเดตให้แสดงข้อความพร้อมชื่อเพลงที่กำลังเล่นอยู่ ดังที่แสดงด้านล่าง ในแบบฝึกหัดนี้ คุณจะใช้ custom iterator นี้ฝึกจัดการข้อผิดพลาด 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
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- สร้าง
Playlistชื่อclassic_rock_playlistจากชื่อเพลงใน listsongsโดยให้classic_rock_playlistสุ่มลำดับเพลงด้วย - ใช้ block
try-exceptภายในลูปwhileเพื่อเล่นเพลงถัดไปใน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!")
____