[Tutor] Program for outputing the letter backward

Hoffmann oasf2004 at yahoo.com
Thu Mar 30 03:14:20 CEST 2006


--- Kent Johnson <kent37 at tds.net> wrote:

> Hoffmann wrote:
> > We are almost there. I changed the code and, at
> least,
> > I got the correct output. However, I also got a
> > traceback. I didn't understand the traceback.
> Could
> > you clarify that?
> > Thanks,
> > Hoffmann
> > ps: The new code:
> > 
> > 
> >>>>vehicle='car'
> >>>>index = -1  #index of the last letter
> >>>>lenght = len(vehicle)
> >>>>last = vehicle[lenght-1]
> >>>>
> >>>>while last >= vehicle[0]:
> > 
> > 	letter=vehicle[index]
> > 	print letter
> > 	index -= 1
> 
> You are still confusing the index of a letter and
> the letter itself.
> 
> In [1]: vehicle = 'car'
> 
> In [2]: last = vehicle[-1]
> 
> In [3]: last
> Out[3]: 'r'
> 
> last is a letter, not a number.
> 
> In [5]: vehicle[0]
> Out[5]: 'c'
> 
> vehicle[0] is also a letter. So when you write
>    while last >= vehicle[0]:
> you are comparing two characters, which is not
> really helpful in the 
> current context. What you really want to do is
> compare the index of the 
> current character with 0. Here is a working version
> in the same style:
> 
> In [6]: index = len(vehicle)-1
> 
> In [7]: while index >= 0:
>     ...:     print vehicle[index]
>     ...:     index -= 1
>     ...:
>     ...:
> r
> a
> c
> 
> The best way to reverse a string is with a slice and
> negative index:
> 
> In [8]: vehicle[::-1]
> Out[8]: 'rac'
> 
> but I'm going to have to leave explanation of that
> to another day or 
> another poster.
> 
> Kent
> 
> 
> _______________________________________________

Hello Guys,

Thank you very much all of you (in special: Kent,
John, and Adam), for the nice explanations about my
excercise. I am a newbie that is studying Python
programming by myself. I appreciated your attention.

See you on my next post :-)

Best,

Hoffmann

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Tutor mailing list