breasking out of a while loop (in an if statement)

David Bolen db3l at fitlinxx.com
Tue Feb 13 20:18:45 EST 2001


Lee Reilly CS1997 <lreilly at cs.strath.ac.uk> writes:

> Hi, I wonder if anyone could be kind enough to point out what I am doing
> wrong here (please see code below).
(...)
> -=---=-=--=-==-=-=-=-==
> while (j!=0):
>     if (radiobutton=='comma'):
>         tempString = string.split(text[i-1], ",")
>     else:
>         tempString = string.split(text[i-1], "\t")
> 
>     matric = string.rstrip(string.lstrip(tempString[0]))
>     SQL = "select * from STUDENTS where matric= '" + matric + "'"
>     result=db_conn.query(SQL)
>     result = len(result)
>     if (result>=3):
>        return "Student with matric value " + matric + " already exists
> in the database"
>        # break
>     else:
>         j=j-1
> -=---=-=--=-==-=-=-=-==
> 
> => Error Type: IndexError
> => Error Value: list index out of range
> 
> I'm using Python with Zope BTW.
> 
> Can anyone see my problem? Any help would be greatly appreciated ;-)

It would help to have the full traceback since that would highlight
the line where the actual error is occuring.  Also, it looks like this
code depends on surrounding code (e.g., where is "i" or "text" set?),
so having more detail about that surrounding code might help.

But given the error, and assuming that the error is actually within
this specific code, then it would seem to me to either be arising from
your reference to "text[i-1]" or "tempString[0]".

In the former case, you should verify that "text" has the contents you
expect and that it has enough entries in any pass through the loop as
indexed by "i-1".

I think the latter case is safe, since from what I can see, using
string.split with a dividing character will always at least produce a
single entry in the list, although it may be an empty string.  But you
might want to verify it in this actual code as well, since at least in
Python 1.5.2, string.split does return an empty list (e.g., if I split
an empty string on the default separator) in some cases, which could
then yield the IndexError when you try to access element 0.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list