Reverse - Practice Makes Perfect


Reverse - Practice Makes Perfect

File “python”, line 13
while n > 0:
IndentationError: unindent does not match any outer indentation level

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

I’m really not sure why I’m getting an indentation error. I’m assuming things were updated last night and (at least for me) the indents are a bit harder to see.

input = ""
while input == "":
	input = raw_input("Enter your text here ", )
#print input
def reverse(x):
	nl = [x]
	n = len(x)
 	rl = []
  #return nl
  while n > 0:
    n = n - 1
    return rl

print reverse(input) 



	nl = [x]
	n = len(x)
 	rl = []
  #return nl
  while n > 0:

these indents don’t match, they should match



Thank you for your reply.

I haven’t changed anything, either I’m going crazy or what I’m seeing on my console isn’t the same as what was copied into my original post.


i was also a bit struggling with the indent, maybe you want to re-indent those lines to ensure its right? Or do you no longer get an indent error?

also, a function ends the moment a return keyword is reached, so your function currently ends in the first iteration of the loop, you want to return rl after the loop (where you currently have str(rl)

also, str() won’t convert list to string, we need to use .join() to achieve this



In the first image, I hadn’t made any changes to my code at all. As per your suggestion I redid the indents, and it fixed that problem. I also made the edits you suggested, thank you! However, now I’m getting this error-
Traceback (most recent call last):
File “python”, line 21, in
File “python”, line 14, in reverse
IndexError: list index out of range


If I understand correctly if a string has a length of 5, the fifth character is in location 4 since Python starts counting from 0. So I swapped the “n = n -1” to put it before the rl.append and set the while condition to “while n >= 0:” So if there word was “abcd”, n would start the loop with a length of 4, subtract 1 to become three, then append the character in the 3rd spot to the list rl. repeat for 2nd, 1st, 0place, and finally exit the loop. However, I’m still getting an error.

Edit 2:
I fixed the .join to “”.join(rl)


I got the code to work. It seems the main problem was that it didn’t want the input for the function to be saved as a list then reversed into a second list. So I removed the first list (nl - in the previous posts) and just used the direct input to store the reverse into the list “rl”. Afterwards I correctly (finally =p) used the .join function to produce the reversed word.