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

Hoffmann oasf2004 at yahoo.com
Wed Mar 29 17:21:52 CEST 2006


--- John Fouhy <john at fouhy.net> wrote:

> On 29/03/06, Hoffmann <oasf2004 at yahoo.com> wrote:
> > Hi John,
> >
> > (1) vehicle[index] is: 'c'
> > (2) If index = index = 1, so vehicle[index]
> becomes:
> > 'a'
> 
> What I'm getting at here is that, by changing index,
> we can change
> which letter we are looking at.  And index is a
> number, which means
> it's easier to reason about than letters are.
> 
> Let's have a look at a possible solution:
> 
> >>> vehicle = 'car'
> >>> index = 2
> >>> print vehicle[index]
> r
> >>> index = 1
> >>> print vehicle[index]
> a
> >>> index = 0
> >>> print vehicle[index]
> c
> 
> Notice that the three print statements are
> identical.  That suggests
> we could write the code in a loop, with 'print
> vehicle[index]' in the
> body of the loop.  Can you have a go at that?
> 
> --
> John.
> _______________________________________________
 
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 


__________________________________________________
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