Reverse Help


#1


Practice Makes Perfect: 7. reverse

I am getting the following error:
File "python", line 5
return reversed_text
^
IndentationError: unindent does not match any outer indentation level

When I move the indention I get "!" returned instead of "!nohtyP"


def reverse(text):
   reversed_text = ""
   for i in range(len(text)):
        reversed_text += text[len(text)-1-i]
    return reversed_text


#2

I copy and pasted your code into my browser and I think the line holding your for loop might be indented only three spaces instead of four(1 tab)

Could be my browser being weird though


#3

Thank you so much. Was killing me.


#4

As a general rule, indentation is 4 spaces, but this is not specified by Python. It only looks at any indentation as being a change in scope. Three spaces is just a valid as four, or two, or one. The key is consistency. Had the return line been only three spaces, there would be no problem.


#5

Could someone please explain this line of code? I am trying to figure out what it means but am a bit confused.
Thank you!


#6

len(text) - 1 is the index of the last element in text (always one less than length).

When i starts at 0, given a length of 10, the indices inside the loop become,

10 - 1 - 0  => 9
10 - 1 - 1  => 8
...
10 - 1 - 8  => 1
10 - 1 - 9  => 0

The indices are in reverse order, meaning the elements are retrieved in reverse order.