Reverse


#1


https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#

Oops, try again. Did you create a function called reverse? Your code threw a "local variable 'txtrv' referenced before assignment" error.


I expected that the function would (in a loop) add the (each time) last letter of the string to a new string, but I don't understand why it doesn't.


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


#2

you try to add text[len(text)-1] to a undefined variable (txtrv), maybe you should define txtrv first? Going by your logic, it should be an empty string


#3

Aha. So I defined the txtrv string by "" (empty string, if I'm right). I also tried the argument None, but I don't know the difference between them (I get the same error from both).
So now my code is

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

and the error is :
Does your reverse function take exactly one argument (a string)? Your code threw a "unsupported operand type(s) for -=: 'str' and 'str'" error.

This means the operators += and -= are not used in strings, right? So I have to convert my string to a list? (I was trying to avoid this)


#4

well, += is used to concatenate string, -= isn't used

well, there are several ways to solve this problem, if you really want to avoid lists, its possible, for example you could use range() to loop in reverse over string


#5

Great! I modified my code as follows, and now it worked without having to turn my string to a list! Thanks for the help!

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

#6