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

Reg the morse code challenge task 1 of 1. I am entering this code which should give the correct output but i get error

The code below is my code which I think should give the correct answer but somehow your system says that the output is not what is expected. When i run this code on my python installation it gives the correct and desired output. Can someone explain what is wrong?

class Letter: def init(self, pattern=None): self.pattern = pattern self.newstr='' self.l=len(pattern)

def __str__(self):
    k=1
    for i in self.pattern:
        self.newstr+='dot' if i=='.' else 'dash' 
        if k!=self.l:
            self.newstr+='-'
        k+=1
    return self.newstr 

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

morse.py
class Letter:
    def __init__(self, pattern=None):
        self.pattern = pattern
        self.newstr=''
        self.l=len(pattern)


    def __str__(self):
        k=1
        for i in self.pattern:
            self.newstr+='dot' if i=='.' else 'dash' 
            if k!=self.l:
                self.newstr+='-'
            k+=1
        return self.newstr 

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

1 Answer

Steven Parker
Steven Parker
231,269 Points

Since "self.newstr" is not cleared at the beginning of the "__str__" method, it may still contain the results of a previous method call and add on to it.

Optionally, "newstr" could be a local variable of the method and not an instance variable. The same could be done with "self.l".

Got it! Thanks. It works now.