7/15 Loop doesn't seem to...uhm...loop, I guess


#1

My code goes like this:

def reverse(text):
count = len(text)
while count > 0:
return text[len(text)-1]
count -= 1


So, do I miss the "else" part or what? I only get exclamation mark as an output and that's it.


#2

First of all, please use indentations. The second thing — your function always breaks after return.


#3

Here is your code. I have commented in there why it doesn't work

def reverse(text):
    # we start at the end --> awesome
    count = len(text)
    # loop begins
    while count > 0:
        
        # but wait whenever we call return in a function
        # the function terminates(we are done with it)
        # Hence after we return the last letter,the while
        # loop terminates
        return text[len(text)-1]
        
        #this count variable is UNREACHABLE
        #because method is terminated
        count -= 1
    
print reverse("make") ##--> e
print reverse("codeacademy") ##--> y

You can also test it HERE


Below is a suggested code

def reverse(text):
    # we start at the end --> awesome
    count = len(text)-1
    #reversed text is initially empty
    reversed_text = ""
    
    #start loop
    while (count >= 0):
        #keep adding to reversed_text
        reversed_text += text[count]
        
        # decrement count
        count -= 1
    #return the final reversed text
    return reversed_text
    
print reverse("make")
print reverse("codeacademy")

You can also run and play with it HERE


In the future when you post code try to select it and press ctrl + k or hit the </> button in the tools pane for easy readability
Another way to format your code with syntax highlighting is to surround the beginning and end of your code with three backquotes each


11/15 count
What´s going on? (insert reference here)
7/19[Fixed] Watch for spelling lol
Help me! please
#4

Thanks so much for the answer! And for the hint about how to indent text )
I've got a question though: why do we make variable 'count' equals to len(text)-1?


#5

Python treats strings as a list of characters. Remember list indices start from 0 to n -1(where n is the length of the list and n-1 is the last element). so when we do count = len(text)-1 it makes sure that we are getting the last element eg say we have

s = "codeacademy"

the length s{ len(s) } is 11

but the last element is at position 10 so we can access it by saying s[10]

To make it more versatile we write it like this s[len(s)-1] --> s[11 -1] = s[10]

this is to ensure that even when the value of s changes we always get the last element

Hope this helps clarify :grinning:


#6

Yeah, it helped a lot! Thank you :relieved:


#7

I almost got there, but not quite. The code below calculates (count - 1) inside the while loop, and if it doesn't contain the break statement, throw the error "reverse(Python!) gives !nohtyP! not !nohtyP" (It works fine with the break statement.)
Why do you need to break if you calculate (count - 1) inside the loop but not outside?

def reverse(text):
    results = ""
    count = len(text)
    while count >= 0:
        results += text[count - 1]
        count -= 1
        if count == 0:
            break
    return results

#8

Wait, also, how do you decide whether to use .append() or ("string" + "string") method? Thx!


#9

@ferretey to explain first it is good to know this

imagine we have s = "code" i can get the last character in s by calling
s[-1] --> 'e'
if we write s[-2] we get 'd' and so on

Now to your code

Lets take text = "python!"

*Note::: text[-1] is '!'*

first count = len(text) --> 6
once we  start the while loop (remember our condition is it should continue as long as count is not < 0)

but whats interesting is this part result+=text[count -1] so

when the value of count gets to 0 then we  would have
result+=text[ 0 -1 ] which is
'!nohtyp'+= text[-1] ---> "!nohtyp!"

so when you add this line

if count == 0:
    break

the loop terminates to prevent the last character from being added.

Also test it out here
Click to go to labs


#10

@rydan So text_string[-1] == text_string[len(text_string) - 1] ?! That's weird, and potentially useful...

Is this identity stable enough to use to reliably iterate through a string backwards? (Provided you correctly instruct it how to stop.)


#11

@ferretey Yep that's true the code snippet below will be true

text_string = "codeacademy"

#this will print true
print (text_string[-1] == text_string[len(text_string)-1]) #true

#12

Hello, does count = len(text)-1 save the last character instead of the whole string with the last character first?(for example '!' instead of '!Python')
Or does it actually just place the last character first so it in the loop can save that character to the string variable and then remove it so it doesn't get added twice?

while count >= 0:               #repeat until there are no characters left?
    results += text[count - 1]  #save the last character in the string variable
    count -= 1                  #remove the character that was just added to the string variable(?)

Is it the right way of thinking or have I misunderstood?


#13

@ericusbravus first

count = len(text)-1 # this is just a number but this number is the same as the index of the last character in text

but

last_character = text[count] # this is what saves the last character in last_character

so when we make this statement

while count >= 0: #we are just checking numbers
    ''' what were are really doing is we are creating a new string
        with this new string we want construct it by adding up the characters
        form the  given text starting from the last and then move to the first
        ----------------------------------------------------------------------
        eg. text = 'code'
        then count = 3
        last_character = text[count] = text[3] = "e"
        ----------------------------------------------------------------------
        we add the last_character to result and in the while loop when we reduce count to 2 , 
        last_character will now be "d" and so on
    '''
      results += text[count - 1]  #save the last character in the string variable
      count -= 1

#14

ahh, okay. That cleared it up for me, thanks for the quick reply. :grin:


#15

Thank you very much for this. I feel quite embarrassed, but reading your post I realised that I either didn't know or forgot that whenever you call 'return' you terminate the function, thus breaking a loop...
I was stuck for quite some time in other similar exercises with functions with counters that didn't work and I just couldn't see why!... now I get it!
Thank you for unstucking me :smiley:


#16

This code works as well :

   def reverse(text):
       r_string = []
       l_string=len(text)-1
       for i in range(l_string,-1,-1):
          r_string.append(text[i])
       return "".join(r_string)

    print reverse("Python!")
    print reverse("Having fun with Python on code Academy!")

#17

hi, i wrote just like yours, but it failed, Could you help me find the problem?
THanks!

Here is my code:

def reverse(text):
m =len(text)-1
word=[]
for i in (m,-1,-1):
word.append(text[i])
return "".join(word)

**print reverse("Python!")**

it reminds me that, error occurs when reverse Python! it turns out "!!!" instead of " !onhtyP"


#18

The problem is here on this line

for i in (m,-1,-1):

it should be rather

for i in range(m,-1,-1):

#19

Hello, I use this code, it's similar to others, but i use .insert for putting letters to list and its much easier.
While looping every letter become first in list and in the end the word will be reverse.

def reverse(text):
    dic=[]
    for t in text:
        dic.insert(0,t)
    return "".join(dic)

#20

@rybov that's a good idea you can also try this, using list comprehension

def reverse(text):
    return "".join([text[x] for x in range(len(text)-1,-1,-1) ])

print reverse("codeacademy")