[Tutor] Program for outputing the letter backward - almost there!

Adam adam.jtm30 at gmail.com
Thu Mar 30 01:39:57 CEST 2006


> Hi John,
>
> 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
>
>
> r
> a
> c
>
> Traceback (most recent call last):
>   File "<pyshell#40>", line 2, in -toplevel-
>     letter=vehicle[index]
> IndexError: string index out of range

while last >= vehicle[0]:

The problem is is that neither vehicle[0] nor last change during the
loop so it is always satisified and index eventually becomes a number
that doesn't correspond to an index of the string.
I would suggest something along these lines instead:

for i in range(len(vehicle)-1, -1, -1):
    print vehicle[i]

which is basically what my list comp did but printing out the letters
rather than returning a list


More information about the Tutor mailing list