more newbie help needed
Steve Holden
steve at holdenweb.com
Mon Nov 14 16:10:50 EST 2005
john boy wrote:
[top-posting corrected]
>
> Steve Holden <steve at holdenweb.com> wrote:john boy wrote:
>
>>using the following program:
>>
>>fruit = "banana"
>>index = 0
>>while index < len (fruit):
>>letter = fruit[index-1]
>>print letter
>>index= index -1
>>
>>this program is supposed to spell "banana" backwards and in a vertical patern...it does this....but after spelling "banana" it gives an error message:
>>refering to line 4: letter = fruit[index-1]
>>states that it is an IndexError and the string index is out of range
>>Anybody know how to fix this?
>>
>
> Change the termination condition on your loop. If you print out the
> values of index as the loop goes round you'll see you are printing
> characters whose index values are -1, -2, ..., -6
>
> Unfortunately -7 is less than -6, so your loop keeps on going, with the
> results you observe.
>
> Note, however, that there are more pythonic ways to perform this task.
> You might try:
>
> for index in range(len(fruit)):
> letter = fruit[-index-1]
> print letter
>
> as one example. I'm sure other readers will have their own ways to do
> this, many of them more elegant.
>
thanks for your example....but for information purposes so I can grasp
the basics....could you give me an example of how I could terminate the
"while" loop
Well in this case, when fruit == "banana" the last value you want to use
is -6 - you've already seen that using -7 causes the interpreter to
raise an exception.
So you could use, for example,
while -index <= len(fruit)
though I haven't tested that. Basically you need to work out a condition
that's true for all useful values of index and false for the first
non-useful value.
By the way, I've copied this reply to the list. It's customary to keep
follow-ups on the list, that way if I'd been too busy to answer somebody
else might have been able to help.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list