StopIteration 오류 처리하기
이전 연습 문제의 Playlist 클래스가 현재 재생 중인 곡 제목을 출력하도록 업데이트되었습니다. 아래 코드를 참고하세요. 이 커스텀 이터레이터를 사용하여 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
이 연습은 강의의 일부입니다
Python 중급 객체 지향 프로그래밍
연습 안내
songs리스트의 제목들로 구성된classic_rock_playlist라는Playlist를 생성하되, 곡이 섞이도록 설정하세요.while루프 안에서try-except블록을 사용해classic_rock_playlist의 다음 곡을 재생하세요.StopIteration오류를 처리하도록try-except로직을 수정하고, 메시지를 출력한 뒤 루프를 종료하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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!")
____