เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การจัดการข้อผิดพลาด 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 จากชื่อเพลงใน list songs โดยให้ 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!")
		____
แก้ไขและรันโค้ด