Reverse- magically appearing letters


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096


Here's the error:
Oops, try again. Your function fails on reverse("Python!"). It returns "cba!nohtyP" when it should return "!nohtyP".


It looks like it works except... Where are all of those extra letters coming from? It looks like either the "backwards" list isn't really empty when the function starts running or the text input is screwed up... What am I doing wrong?


backwards = []
 
def reverse(text):
    n = len(text)
    while n > 0:
        backwards.append(text[n-1])
        n -= 1
    return "".join(backwards)


#2

It looks like two tests were run, abc and Python!. Because this list is declared outside of the function, it is not reset to empty with each run. Move this inside the function and it will work.


#3

It's because your backwards = [] is outside the function. Sometimes, if you have multiple function calls, the backwards will also store the backwards output of the other calls.

eg.

backwards = []

 
def reverse(text):
  
    n = len(text)
    while n > 0:
        backwards.append(text[n-1])
        n -= 1
    return "".join(backwards)
    
print reverse("Hello World")
print reverse("Hey!")

=>
dlroW olleH
dlroW olleH!yeH #the Hello World backwards got stored in backward before

Just put backward = [] inside your function and before your loop.


#4

Yes, it works now. Thank you


#5

Though I have to ask... Why does that matter as long as the list is emptied before the function is run?


#6

backward is a local variable and has no purpose in global scope Consequently it should be defined inside the function that uses it.


#7

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