Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Kade Carlson
Kade Carlson
5,928 Points

I'm not understanding why my code is wrong here

I'm not sure if I understand the question. I also don't know how I could improve my logic to make it work for this challenge

morse.py
class Letter:
    def __init__(self, pattern=None):
        self.pattern = pattern

    def __str__(self):
        for item in pattern:
            if item == '.':
                return "dot"
            else:
                return "_"

            .join(item, "-")


class S(Letter):
    def __init__(self):
        pattern = ['.', '.', '.']
        super().__init__(pattern)

2 Answers

A few things,

First, your logic is good, first using a for loop then testing each iterable with an if clause. however, you can't just return the string because that is not the same as returning 'dot-dot-dot' in a single string, plus it breaks the for loop when you return something mid-loop.

You'd have to store the results in another variable, like a list, and then joining it with the join method.

see the code below and see if it makes sense. :)

class Letter:
    def __init__(self, pattern=None):
        self.pattern = pattern

    def __str__(self):
        string_morse = []  # Creates an empty list for later appending
        for symbol in self.pattern:  # Remember, pattern is a method of self. You have to use self.pattern
            if symbol == '.':
                string_morse.append('dot')  # Append string to the list we previously created.
            else:
                string_morse.append('dash')
        return '-'.join(string_morse)  # Joins the list together using '-'


class S(Letter):
    def __init__(self):
        pattern = ['.', '.', '.']
        super().__init__(pattern)

Hope this helps!

Kade Carlson
Kade Carlson
5,928 Points

Makes sense! Thank you!