शुरू करेंमुफ़्त में शुरू करें

StopIteration error को संभालना

पिछले अभ्यास की Playlist क्लास को अपडेट कर दिया गया है ताकि यह चल रहे मौजूदा गाने को शामिल करते हुए एक संदेश प्रिंट करे. यह नीचे दी गई है. इस कस्टम iterator का उपयोग करके, आप StopIteration exception को सहज तरीके से संभालने का अभ्यास करेंगे. मज़ा लीजिए!

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

यह अभ्यास पाठ्यक्रम का हिस्सा है

Intermediate Object-Oriented Programming in Python

पाठ्यक्रम देखें

अभ्यास निर्देश

  • songs लिस्ट में दिए गए टाइटल्स से बनी एक Playlist बनाएँ जिसका नाम classic_rock_playlist हो; ध्यान रखें कि classic_rock_playlist में गाने shuffle हों.
  • while लूप के अंदर try-except ब्लॉक का उपयोग करके, classic_rock_playlist में अगला गाना चलाएँ.
  • try-except लॉजिक को अपडेट करें ताकि StopIteration error को संभाला जा सके, एक संदेश प्रिंट हो, और लूप से बाहर निकला जाए.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

# 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!")
		____
कोड संपादित करें और चलाएँ