problem adding list values

Gerard Flanagan grflanagan at yahoo.co.uk
Thu Dec 22 15:04:03 EST 2005


David M. Synck wrote:

> Hi all,
>
> I am fairly new to Python and trying to figure out a syntax error
> concerning lists and iteration through the same. What I am trying to do is
> sum a list of float values and store the sum in a variable for use later.
>
> The relevant code looks like this -
>
> def getCredits():
>
>     """ This function asks the user to input any credits not shown on their bank statement
>
>     It returns the sum(converted to float) of the entered credits """
>
>     global credits
>     credlist = []
>     credits = 0.0
>     temp = 0.0
>     print "Now you need to enter any credits not shown on your bank statement \n"
>     print "Please enter a zero (0) once all credits have been entered \n"
>     raw_input("Hit 'Enter' to continue \n")
>     temp = float(raw_input("Please enter the first credit \n"))
>
>     while temp != 0:
>         credlist.append(temp)
>         temp = float(raw_input("Please enter the next credit \n"))
>
>     i = 0
>     for i in credlist:
>         credits += credlist[i]
>         i = i + 1
>
>     return credits
>


David

replace these lines:

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

with these:

for i in credlist:
    credits += i


the 'for' loop handles the indexing for you.  maybe read 'for' as
'foreach' until it becomes more familiar.

Hope that helps.

Gerard




More information about the Python-list mailing list