Reverse function is working but not accepted



I am doing the codecademy tutorial and I got stuck during a lesson where I have to reverse a word. My function works when I test it myself, but when the program checks it by calling reverse("Python!") it returns "cba!nohtyP". That is not the case when I call it the same way. Then it returns correctly "!nohtyp". Can anyone please help me what is the issue with my code?

The message errors are: There are none, just the program does not believe that it is working :smiley:

Oops, try again. Your function fails on reverse("Python!"). It returns "cba!nohtyP" when it should return "!nohtyP".

reversed_list = []

def reverse(text):
    length = len(text) - 1
    while length >= 0:
        length -= 1
    result = ""
    for i in reversed_list:
        result += i
    return result


Put this inside (empty list) the function!


Thank you! That solved my problem! Do you have any explanation why it is an issue to have it outside the function?


if you call the function multiply times, the list will keep leftovers from earlier function calls (when the list is declared outside the function)

the exercise calls the function multiply times to validate your function reverse correctly


reversed_list = [] is a global variable.
When CC interpreter checks it for various inputs,It already used to have previous string value and the overall o/p looks messy.

This one works fine for one input(not on CC interpreter) but when you call function on various parameters ,It will print gibberish(As string is get added to past values)

also check this..


visualization of the code when list is global and we called function one time.. (it works fine in this case)

Visualization of code when you call function multiple times and list still global

(you can check what happens when you make list local,just copy-paste your code there and visualize the whole execution process)


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