Reverse


#1

Hello, I know that I am overcomplicating my code. I would appreciate some guidance on how to simplify what I already have. Thanks in advance for the help.

My idea is to (line 1) create a function; (2) create an empty string; (3) create a ‘while’ condition that will execute my loop until it has gone through the entire string; (4) target every character in the string; (5) append the string characters starting from the last character; (6) lower the character count by 1; and then return and print the reversed string.

My error message is not very helpful
"Did you create a function called reverse? Your code threw a “local variable ‘i’ referenced before assignment” error."


def reverse(text):
    new_string = ''
    while i > 0:
        for i in range(len(text)):
            new_string.append(i[:len(text)])
            i -= 1
    return new_string
    
print reverse


#2

str has no attribute, append.

By their nature, strings are immutable. But, we can replace them any time with another string.

new_string += ...

This will create a new string from the old with content concatenated, then replace the old one with the new one.


#3

It’s because i is a variable that hasn’t been assigned a value. You need to say what i is equal to first.


#4

Thank you, I will take out the while loop since that’s where the problem begins


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.