7. Reverse



Hello, I’ve been stuck at this exercise. Please help.

def reverse(text):
    rev_word = "" 
    length = len(text)
    for i in range(0,length):
        rev_word = rev_word + str(text)[length-i]
    return str(rev_word)

File "python", line 5
SyntaxError: can't assign to function call

Oops, try again. Did you create a function called reverse? Your code threw a "global name 'reverse' is not defined" error.

Why does it think that function “reverse” is not defined if it IS?
Sure, I can solve this exercise with use of list and .append() like everyone else do in related topics, but concatenation should be viable too and I need to know what’s wrong here.


I try your code and here is the outpout error :

Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!

this error generate because length of text , if we take for example text ‘test’ the lenght is 4 , so if we try to output the fourth lettre our code is “test”[3] not “test”[4] we begin by 0 not 1


I know, but i tried to test “for i in range(0,length): print i” for separate string and it printed numbers from 0 to 3, so indexation is OK imo; length - i goes from 3 to 0, because the starting i is 0.
Can you point out what do I need to change?
No matter how I change the code there’s only “reverse is not defined” or “string index out of range”.


nvm, I solved the problem by changing the program so there’s i instead of length-i, but the cause of error is unknown

Maybe it’s a bug, because things like “i print a b c in this order and it prints c a b” happened a few times anyway

7. reverse help

this how i correct it ; so [length-i-1] start from 3 not 4

def reverse(text):
    rev_word = "" 
    length = len(text)
    print length
    for i in range(0,length):
        rev_word = rev_word + str(text)[length-i-1]
    return str(rev_word)
print reverse("text")

7. reverse help
Another way of doing it..
def reverse(text):
        x, new = str(text), ""
        c = len(x)
        while c > 0:
    	    c -= 1
    	    new = new + x[c]
        return new


Here’s how one would do it in order to understand how to effectively use lists to store each character of the string. This way may require more lines of code, but I want to ensure it includes the usage of lists and the for and while loops.

def reverse(text):
    reversed_text = ""
    #put text in a list
    the_list = []
    for char in text:
    n = len(the_list) - 1
    while n >= 0:
        reversed_text += the_list[n]
        n -= 1
    return reversed_text

reverse(raw_input("Enter a string"))