Reverse


#1



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


Error: "Oops, try again. Your function fails on reverse("Python!"). It returns "y" when it should return "!nohtyP". "


I expect it to work just fine.


def reverse(text):
    count = 0
    length = len(text)
    reversing = ""
    for i in text:
        while length > 0:
            count += 1
            back_to_forth = length - count
            reversing = text[back_to_forth]
            length -= 1
    return reversing
            
print reverse("Python!")


#2

reversing = text[back_to_forth]

can you tell me how does it work in the code?is it what you want?


#3

In the code, I had assigned 'back_to_forth' variable an expression to loop through text starting from the last character through the first character.

The line reversing = text[back_to_forth] does as follows according to me:

the value in the corresponding index number (back_to_forth variable) of the text string is assigned to the variable 'reversing' in the consecutive iterations.

To provide an example,

In the word "Python!"

The iterations go in reverse order accessing each character. And as it does, it prints it out in an empty string variable (the variable 'reversing')

The variable: reversing would then contain "!nohtyP"


#4

how can you be sure about that it does the same?what's exactly thing you did to assign the value to reversing ?
why dont you add a print statement after reversing to check?

 reversing = text[back_to_forth]
 print reversing

#5

def reverse(text):
count = 0
length = len(text)
length1 = len(text)
reversing = ""
for i in text:
while length1 > 0:
count += 1
back_to_forth = length - count
reversing = text[back_to_forth]
print reversing
length1 -= 1
return reversing

print reverse("Python!")

Output:

!
n
o
h
t
y
P
P
None

'P' is repeated twice!


#6

reversing = text[back_to_forth]

you need a + sign to store

reversing += text[back_to_forth]


#7

Correct Version:

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

print(reverse('Python!'))


#8

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