My function is returning 'None' instead of the reversed text. I'm having trouble finding the bug in my code- anyone mind pointing out where I might be going wrong?

Much appreciated.


Couldn't see the image in my original post so here it is.


Hi ruybwhiz, the reason why your code does not work is that you have an if condition instead of a loop.

Ok, thanks. But why do I need a loop?

Good question! Going by the logic of your code, what you want to do is:

  1. Begin at the last index, equal to len(text) - 1.
  2. If it's greater than 0, extract the character present there (text[i]) and insert it at the front of our output string (txt += text[i]) (and you don't really need to make txt a list, even a string would work, as I just showed)
  3. Move one index to the left (i -= 1).
  4. Repeat points 2 and 3.

The fourth point is very important for you to note. Remember that you will want to keep extracting characters from the back and pushing them to the front as long as i > 0.

So, you need to understand that whenever you see words like "as long as" or "repeat" in your code flowchart (as I drew it above), you will need to use a loop. You usually use for loop to iterate over a fixed length list. Since this is NOT the case here, we'll use a while loop.

Question for you:

Can you now construct the correct code? :wink: