[Tutor] Program for outputing the letter backward - almost there!
Kent Johnson
kent37 at tds.net
Thu Mar 30 02:25:09 CEST 2006
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
More information about the Tutor
mailing list