While and If messing up my program?

Fredrik Lundh fredrik at pythonware.com
Wed Oct 5 03:14:51 EDT 2005


"CJ" wrote:

>    What does worry me, is that I can't seem to get the program by a
> certain spot. It keeps giving me the same error, and I don't know why.

quite often, exception messages means exactly what they say; if
you get an index error, it's because you're trying to fetch an item
that doesn't exist.

for simple debugging, the "print" statement is your friend:

> ttllst=[4,3,45,3]
> cnto=0
> cntt=1
> rept=-1
>
> print cnto
> print cntt
> print ttllst[cnto]
> print ttllst[cntt]
> choice=raw_input("Begin? ")
> if choice == "yes" or choice == "y":
>     while cnto<>len(ttllst)+1:

           print cnto, cntt, len(ttllst)

>         if ttllst[cnto]==ttllst[cntt]:
>             rept=rept+1
>         if cntt==len(ttllst):
>             print ttllst[cnto],"appears in the list",rept,"times."
>             cntt=-1
>             cnto=cnto+1
>             rept=-1
>         cntt=cntt+1
>     print "done."

with that in place, I get

Begin? y
0 1 4
0 2 4
0 3 4
0 4 4
Traceback (most recent call last):
  File "test.py", line 14, in ?
    if ttllst[cnto]==ttllst[cntt]:
IndexError: list index out of range

which means that your second list index (cntt) is too large.

figuring out how to fix that is left as an etc etc.

</F>

PS.  when you've sorted this out, you might wish to check out the
"count" method on list objects:

>>> help(list.count)
Help on method_descriptor:

count(...)
    L.count(value) -> integer -- return number of occurrences of value






More information about the Python-list mailing list