[Tutor] Help Needed

Alan Gauld alan.gauld at btinternet.com
Wed Jun 17 02:32:50 CEST 2009


"Raj Medhekar" <cosmicsand27 at yahoo.com> wrote
> ... I came up with the code I have included in this email. 

Waaaay to complicated!

> message = raw_input("Enter your message: ")
> 
> print message
> 
> high = len(message)
> low = -len(message)
> 
> begin=None
> while begin != "":
>    begin = int(high)
> 
>    if begin:
>        end = int(low)

you don't need the int calls because lebn returns an int.
But you don't even need begin and end since they are just 
aliases to high and low!

And since you never change begin after assigning to high 
you don't need the loop or the if statement!

All thats left is what is below:

>        print "Your message backwards is",
>        print message[high:low:-1]

But there is a bug because you tried to be too clever
and got confused with the -len() for end.
So for 'hello' you are calling

print 'hello'[5:-5:-1]

but you really needed

print 'hello'[-1:-6:-1]

Look at the description of slicing to see why...

However all you really need to do is

print message[::-1]

and let Python figure out the boundaries itself.

Keep it simple...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list