[Tutor] IndexError: string index out of range
Dragonfirebane at aol.com
Dragonfirebane at aol.com
Tue Nov 2 15:03:49 CET 2004
>>>>index = -1
>>>>while index < len(fruit):
>>>>
>>>>
>... print [index], '\t', fruit[index]
>... index = index - 1
>...
>[-1] a
>[-2] n
>[-3] a
>[-4] n
>[-5] a
>[-6] b
>[-7] Traceback (most recent call last):
> File "<stdin>", line 2, in ?
>IndexError: string index out of range
len(fruit) is positive and index is negative, so index will always be smaller
than len(fruit) . . . you want
>>> index = -1
>>> while abs(index) <= len(fruit):
print [index], '\t', fruit[index]
index -= 1
[-1] a
[-2] n
[-3] a
[-4] n
[-5] a
[-6] b
that way, you're comparing the absolute value of index with the length of
fruit and the loop will end w/o reaching an error
Email: dragonfirebane at aol.com
AIM: singingxduck
Programming Python for the fun of it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20041102/6c74cf6e/attachment.html
More information about the Tutor
mailing list