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लॉजिक को अपडेट करें ताकिStopIterationerror को संभाला जा सके, एक संदेश प्रिंट हो, और लूप से बाहर निकला जाए.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# 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!")
____