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

name reverse task- problem

name = input("write your name: ")

for letter in name: a_list = [letter] print(letter)

num = len(name) print(num) #checking lenght of the name

for letter in range((num, 0, -1): #reversing the name print(a_list[letter])

2 Answers

Steven Parker
Steven Parker
242,770 Points

It's hard to decipher the unformatted code, but this stood out for me: "a_list = [letter]". This would create a new list containing a single letter each time, which is probably not what you want.

You probably want to construct a new string, which might be done using concatenation like this:

reversed = ""
for letter in name:
    reversed = letter + reversed

And for future questions, always format any code using Markdown and provide a link to the course page you are working with.

I don't understand why we write reversed = "" like... there is nothing in-between "...

Steven Parker
Steven Parker
242,770 Points

That's, right, there is nothing between the quotes. That creates the variable and starts it out holding an empty string.

Then, inside the loop, it won't cause an error on the first pass when it is combined with the first letter.

At first, I thought that if I would make a list of letters I can print it reversed(maybe with the help of ranges...) Anyway now it works and it is much shorter Thank you!

But still ... it doesn't seem so intuitive :( cause when I print the variable letter in the for loop it is all in the correct order... while when I concatenate it with an empty string it is reversed...how?

Steven Parker
Steven Parker
242,770 Points

It's due to the order of concatenation, "letter + reversed". Each "letter" is being added in front of the reversed list, which changes the order. If you did it the other way ("reversed + letter") then you would get another string just like you started with.

Later on, when you learn about Slicing (if you haven't already), you'll come across another way of reversing a given word -

>>> word = "hello"
>>> rev = word[::-1]
>>> rev
'olleh'