problem adding list values

mrmakent at cox.net mrmakent at cox.net
Thu Dec 22 16:01:32 EST 2005


Glad to help.  Your relevant code:

>     i = 0
>     for i in credlist:
>         credits += credlist[i]
>         i = i + 1

credlist is your list of credits, which are floating point numbers.
You use a for-loop to iterate thru this list of floating point numbers,
so each time thru the loop, the variable 'i' is set to the next
floating point number from the list.  'i' is NOT being set to a
sequence of integers starting with '0'.  You then try to index into
credlist using the floating-point number set in 'i' as the index, which
you can't do.  I presume you are used to the for-loop behavior from
some other language.

To rewrite this code to correctly use a for-loop, try something like:

totalCredits = 0.0

for credit in credlist:
    totalCredits += credit

Alternatively, you can use the build-in function 'sum' to sum a
sequence of numbers:

totalCredits = sum(credlist)

Python isn't a hard language to pick up, but there are some significant
differences from other languages like C or Basic.  You're off to a good
start.




More information about the Python-list mailing list