---
id: 68b99aa2f4444c86af78c101
title: Step 41
challengeType: 20
dashedName: step-41
---

# --description--

Indent your existing `for` loop by one level so that it runs when the catalogue has movies in it. Then, replace `self.items` with `movies` to iterate over movies only.

# --hints--

You should indent the existing `for` loop by one level and replace `self.items` with `movies` to iterate over movies only.

```js
({
  test: () => runPython(`
    loop = """for i, movie in enumerate(movies, 1):
        result += f'{i}. {movie}\\\\n'"""
    assert _Node(_code).find_class("MediaCatalogue").find_function("__str__").find_ifs()[1].find_body().is_ordered("result += '=== MOVIES ===\\\\n'", loop)
  `)
})
```

When `self.items` contains `Movie('Dances with Wolves', 1990, 'Kevin Costner', 224)` and `Movie('Annie Hall', 1977, 'Woody Allen', 93)`, your `__str__` method should return `Media Catalogue (2 items):\n\n=== MOVIES ===\n1. Dances with Wolves (1990) - 224 min, Kevin Costner\n2. Annie Hall (1977) - 93 min, Woody Allen\n`.

```js
({
  test: () => runPython(`
    import io
    import sys
        
    captured_output = io.StringIO()
    sys.stdout = captured_output

    _catalogue = MediaCatalogue()
    _catalogue.add(Movie('Dances with Wolves', 1990, 'Kevin Costner', 224))
    _catalogue.add(Movie('Annie Hall', 1977, 'Woody Allen', 93))
    print(_catalogue)
        
    sys.stdout = sys.__stdout__
    output = captured_output.getvalue()

    _expected = """Media Catalogue (2 items):

    === MOVIES ===
    1. Dances with Wolves (1990) - 224 min, Kevin Costner
    2. Annie Hall (1977) - 93 min, Woody Allen
    """
    assert _expected in output
  `)
})
```

When `self.items` contains `Movie('Barry Lyndon', 1975, 'Stanley Kubrick', 184)` and `Movie('Fahrenheit 451', 1966, 'Francois Truffaut', 112)`, your `__str__` method should return `Media Catalogue (2 items):\n\n=== MOVIES ===\n1. Barry Lyndon (1975) - 184 min, Stanley Kubrick\n2. Fahrenheit 451 (1966) - 112 min, Francois Truffaut\n`.

```js
({
  test: () => runPython(`
    import io
    import sys
        
    captured_output = io.StringIO()
    sys.stdout = captured_output

    _catalogue = MediaCatalogue()
    _catalogue.add(Movie('Barry Lyndon', 1975, 'Stanley Kubrick', 184))
    _catalogue.add(Movie('Fahrenheit 451', 1966, 'Francois Truffaut', 112))
    print(_catalogue)
        
    sys.stdout = sys.__stdout__
    output = captured_output.getvalue()

    _expected = """Media Catalogue (2 items):

    === MOVIES ===
    1. Barry Lyndon (1975) - 184 min, Stanley Kubrick
    2. Fahrenheit 451 (1966) - 112 min, Francois Truffaut
    """
    assert _expected in output
  `)
})
```

Your `__str__` method should return `Media Catalogue (empty)` when `self.items` is empty.

```js
({
  test: () => runPython(`
    import io
    import sys
        
    captured_output = io.StringIO()
    sys.stdout = captured_output
        
    print(MediaCatalogue())
        
    sys.stdout = sys.__stdout__
    output = captured_output.getvalue()
        
    assert "Media Catalogue (empty)" in output
  `)
})
```

# --seed--

## --seed-contents--

```py
class MediaError(Exception):
    """Custom exception for media-related errors."""

    def __init__(self, message, obj):
        super().__init__(message)
        self.obj = obj

class Movie:
    """Parent class representing a movie."""
    
    def __init__(self, title, year, director, duration):
        if not title.strip():
            raise ValueError('Title cannot be empty')
        if year < 1895:
            raise ValueError('Year must be 1895 or later')
        if not director.strip():
            raise ValueError('Director cannot be empty')
        if duration <= 0:
            raise ValueError('Duration must be positive')
        self.title = title
        self.year = year
        self.director = director
        self.duration = duration

    def __str__(self):
        return f'{self.title} ({self.year}) - {self.duration} min, {self.director}'

class TVSeries(Movie):
    """Child class representing an entire TV series."""

    def __init__(self, title, year, director, duration, seasons, total_episodes):
        super().__init__(title, year, director, duration)

        if seasons < 1:
            raise ValueError('Seasons must be 1 or greater')
        if total_episodes < 1:
            raise ValueError('Total episodes must be 1 or greater')
        
        self.seasons = seasons
        self.total_episodes = total_episodes

    def __str__(self):
        return f'{self.title} ({self.year}) - {self.seasons} seasons, {self.total_episodes} episodes, {self.duration} min avg, {self.director}'

class MediaCatalogue:
    """A catalogue that can store different types of media items."""

    def __init__(self):
        self.items = []

    def add(self, media_item):
        if not isinstance(media_item, Movie):
            raise MediaError('Only Movie or TVSeries instances can be added', media_item)
        self.items.append(media_item)

    def get_movies(self):
        return [item for item in self.items if type(item) is Movie]

    def get_tv_series(self):
        return [item for item in self.items if isinstance(item, TVSeries)]
    
    def __str__(self):
        if not self.items:
            return 'Media Catalogue (empty)'
        
        movies = self.get_movies()
        series = self.get_tv_series()

        result = f'Media Catalogue ({len(self.items)} items):\n\n'
--fcc-editable-region--
        if movies:
            result += '=== MOVIES ===\n'
        for i, movie in enumerate(self.items, 1):
            result += f'{i}. {movie}\n'
--fcc-editable-region--
        return result

catalogue = MediaCatalogue()

try:
    movie1 = Movie('The Matrix', 1999, 'The Wachowskis', 136)
    catalogue.add(movie1)
    movie2 = Movie('Inception', 2010, 'Christopher Nolan', 148)
    catalogue.add(movie2)

    series1 = TVSeries('Scrubs', 2001, 'Bill Lawrence', 24, 9, 182)
    catalogue.add(series1)
    series2 = TVSeries('Breaking Bad', 2008, 'Vince Gilligan', 47, 5, 62)
    catalogue.add(series2)

    print(catalogue)
except ValueError as e:
    print(f'Validation Error: {e}')
except MediaError as e:
    print(f'Media Error: {e}')
    print(f'Unable to add {e.obj}: {type(e.obj)}')

```
