Hi all,

I'm completely new to programming and am finding this section 15: Practice makes Perfect really difficult. I know it's meant to be a recap, I've applied myself and attempted to figure out the exercises as much as possible but just feel as though I am missing something quite obvious in this one and I just don't know what it is. I've read through the forum for ideas but want to try avoid just copying somebody else's answer.

At the minute I feel as though my code is close but I am getting stuck in an infinite loop.

I think it's something to do with the while loop, which I'm not completely sure if I've used it correctly.

def reverse(text):
    word = " "
    length = len(text)
    for i in range(0, length):
            while length >= 0:
                word += text[(length - 1) - i]
                if length == 0:
            return word
    print reverse("wahahahahaha@!@!@!@")

Thanks in advance for any help, as I mentioned I'm finding this section quite difficult.


What's the condition for the while-loop to stop? Something would have to change during the loop so that eventually it stops, yes? Is that change happening during the loop? Where?

Keep in mind that things don't fall into place and go click when you write code, because there's no right answer to anything. There's just you describing what you want to happen, and if that description is off, then the execution will also be off. You need to start with your own intentions, coming up with a series of steps that you are convinced will have the desired effect. So when things don't behave the way you want, you gotta consider exactly what should have happened and then start comparing what was happening, to what you have decided should happen, or indeed, maybe your intentions don't add up and you have to start by changing those.


hope my reply isn't too late

Anyway, you have to put statement that would tend towards ending your while loop.
In your case, your loop states "while length >= 0"
Well, length would always be greater than or equal to 0, unless you do something about it. You should add "lenght - = 1" which would decrement your loop steadily till it reaches 0. Then the while loop condition is fulfilled and breaks

see below a simplified version of your code and answer

def reverse(text):
word = ""
length = len(text)
while length > 0:
word += text[(length - 1) ]

    length -=1
return word


One more variant

def reverse(text):
word = []
l = len(text)

while l > 0:
    l = l-1
return ''.join(word)


thanks~! The key is ''.join!!! Great idea!


def reverse(name):
find = len(name) - 1
for i in name:
total += name[find]
find -= 1
return total



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