# Reverse 7/15: giving answer but still wrong?

#1

My code is as follows:

``````def reverse(text):
length = len(text)
while length > 0:
if length == 0:
print text[0]
break
else:
print text[length - 1],
length -= 1
return reverse
``````

I’ve made many revisions to this but get roughly the same answer. It says ," Your function fails on reverse(“Python!”). It returns “<function reverse at 0x7f224cc40ed8>” when it should return “!nohtyP”."
Yet, " cba!nohtyP" still prints onto the console so why would it be counting it wrong?
Also, if I add "print reverse(“Python”), my code does print nohtyP but with this error message on the same line…
<function reverse at 0x7fd90307ded8>

Any help would be much appreciated, Thanks.

#2

See the return line? Now check the name of the function. Your code is returning a stub that points to that function.

Now take a closer look. The code is printing what should actually be accumulated so the end result can be returned. For best results, never use the name of the function in your function code, and never return it or you will get an infinite loop. (More will be learned about recursion in future lessons, but until then, heed this advice.)

Question: Is `length` ever going to equal to zero in this scenario? Answer: Not gonna happen; unless, length loses some value before the if statement.

with/without if statement
``````>>> def reverse(text):
length = len(text)
while length > 0:
if length == 0:
print (text[0])
break
else:
print (text[length - 1],end='')
length -= 1
return text[::-1]

>>> reverse('python')
nohtyp'nohtyp'
>>> def reverse(text):
length = len(text)
while length > 0:
print (text[length - 1],end='')
length -= 1
return text[::-1]

>>> reverse('python')
nohtyp'nohtyp'
>>>
``````

Notice that the results of both are the same, and all on the same line. That’s the proof we need to show that the if statement code never runs.

with if statement preceded by lessened length value
``````>>> def reverse(text):
length = len(text)
while length > 0:
length -= 1
if length < 1:
print (text[0])
else:
print (text[length], end='')
return text[::-1]

>>> reverse('python')
nohtyp
'nohtyp'
>>>
``````

The above prints on two lines, which means the if statement code is running.

Ignore the return line. I used that for comparison only and it is not meant to be part of this code.

When we get it to run as expected, it’s a nifty little algo for printing in reverse. Nice job. Now go back and accumulate the result without printing inside the function. Have it return a string to the caller and print it there.

``````print (reverse('Python!'))
``````

Using a function that returns a string let’s us do goofy things like this…

``````>>> print ("{} {} {} {} {} {}".format(reverse('and'),reverse('now'),reverse('for'),reverse('something'),reverse('completely'),reverse('different')))
dna won rof gnihtemos yletelpmoc tnereffid
>>>
``````

If that looks a little repetitive, it was on purpose, so we can see it in a more Pythonic form using techniques you will learn in time so don’t pressure yourself or get off track, just now.

``````>>> text = "and now for something completely different".split()
>>> form = "{} " * len(text)
>>> print (form.format(*[reverse(x) for x in text]))
dna won rof gnihtemos yletelpmoc tnereffid
>>>
``````

But, the purpose of this exercise is to study what we’ve learned and put it to work for us. Advancing our pursuits should take a steady course, and not start in the deep end. Learn those alogrithms.

#3

Thank you, I modified the code and now it works with…

``````def reverse(text):
length = len(text)
word = ""
while length > 0:
length -= 1
word += str(text[length])
return word
print reverse("Python")
``````

Would you say that most ‘while’ loops (at least for the future lessons of code academy) would involve establishing a variable with a blank value before the ‘while’ loop that is then added to later on? Thanks again.

#4

In cases where accumulation (or diminishment) is involved, yes. We need to have an initialized variable that can receive new assignments. If we didn’t initialize `word` as a variable the augmentation assignment (`+=`) in the loop would raise an exception…

``````UnboundLocalError: local variable 'word' referenced before assignment
``````

#5

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