Practice makes perfect 7/15 stuck! where to go from here?


This is my code, and it prints abcd, but where can I go from here, Im stuck…what tools can I use to reverse the word?

def word(text):
    letters = ""
    for letter in text:
      letters += letter
    return letters
print word("abcd")


You could loop in reverse order?


but how do you loop in reverse?

Btw, this is from the lesson - “You may not use reversed or [::-1] to help you with this.”


you could get the length of the string -1 (strings are zero indexed based) and then use a for in range() loop or a while loop


I was also thinking abour range in a for loop, somehow using the indexes of each charatcher with enumerate function , modulo them by 10 and assigning the remainders, which represent each character, to a variable and then print it out, but Im having a really hard time doing that…maybe be Im way off…or maybe its impossible…


^ is the only good bit i read in your answer. Use range() to loop in reverse of the string, then use the integers produced by range as indexes to access characters from text and add them to letters. This will cause the string to reverse


thats the part Im havig problem with, but just a minute ago I took a look at the link provided by Codecademy explaining how to loop through text starting from the last character using range, and I see that I’ve totally forgot about using STEP inside range, so I’ll try something with that for a few hours and see how that goes :slight_smile:


you need step for range, because default step is +1, which is no good for looping in reverse


But if I put the minus operator infront of step, it counts down like we want to…I just tested it like this…

n = “qwert”
print range(len(n) - 1, 0, - 1)

and it gave me [4, 3, 2, 1]


yes, that is the whole idea? -1 is good for step value for your loop. I just mentioned that default (when you don’t provide step manually) is + 1 (which is no good for your case at the moment)


Oh ok, I thought you meant that I shouldn’t use step at all, my bad


So the question now is, how to turn those numbers into the letters, because if I do the str() like you see in my code, I get 321 printed out…

def word(text):
letters = “”
for letter in range(len(text) - 1, -1, - 1):
letters += str(letter)

return letters

print word(“abcd”)

Im thinking something like, if letter == text[]: , assign and print ?


OMG I did it!!! But Im getting an error from Codecademy saying:

Did you create a function called reverse? Your code threw a “global name ‘reverse’ is not defined” error.

Any idea why?

My code:

def word(text):
letters = “”
for letter in range(len(text) - 1, -1, - 1):
x = letter
letters += text[x]
return letters
print word(“abcd”)


You didn’t name your function reverse


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.