On 02/06/2012 02:05 PM, myles broomes wrote:
Im trying to code a program where the user enters a message and it is returned 
backwards. Here is my code so far:





message = input("Enter your message: ")

backw = ""
counter = len(message)

while message != 0:
     backw += message[counter-1]
     counter -= 1
print(backw)
input("\nPress enter to exit...")





I run the program, type in my message but get back the error code:

'IndexError: String out of range'

I was thinking that maybe the problem is that each time a letter is taken from 
'message' and added to 'backw', the length of message becomes a letter shorter 
but for whatever reason the variable 'counter' doesnt change when its supposed 
to be minused by 1 letter so its always bigger than message if that makes 
sense. Any help is much appreciated and thanks in advance.

Myles Broomes
                                        

First, what's the python version and OS? If you run that program under 2.x, it'll quit a lot sooner. So I figure Python 3.2

Next, don't retype the message, copy& paste it. Your retype missed an important word of the message, and you didn't include the traceback, which is also important.

Now to your problem: You never change message, so the while loop never terminates (except with the exception when it tries an index that's too far negative. The obvious answer is to terminate the loop when counter goes negative. But it might also be readable to terminate it when the two strings have the same length.

There are many other ways to reverse a string, but I wanted to show you what went wrong in this particular code.

If I were an instructor, the next thing I'd suggest is to ask you how to use a for-loop, instead of a while. Or to look up the slice syntax, and see what the restrictions are of getting substrings from that.

--

DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to