problem adding list values

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David M. Synck

    problem adding list values

    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

    And the syntax error I get is this -

    Traceback (most recent call last):
    File "./BankReconciler_ Rev1.py", line 129, in ?
    main()
    File "./BankReconciler_ Rev1.py", line 116, in main
    getCredits()
    File "./BankReconciler_ Rev1.py", line 60, in getCredits
    credits += credlist[i]
    TypeError: list indices must be integers


    If anyone can point me in the right direction, I would greatly appreciate
    it.

    Thanks in advance
  • Gerard Flanagan

    #2
    Re: problem adding list values


    David M. Synck wrote:
    [color=blue]
    > 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
    >[/color]


    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

    Comment

    • Dave Hansen

      #3
      Re: problem adding list values

      On Thu, 22 Dec 2005 19:43:15 GMT in comp.lang.pytho n, "David M. Synck"
      <dmsynck@verizo n.net> wrote:

      [...][color=blue]
      > 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"))[/color]

      Here you're building credlist as a list of floats.
      [color=blue]
      >
      > i = 0[/color]

      This is wasted effort
      [color=blue]
      > for i in credlist:[/color]

      You've asked to loop through credlist, so each value of i is going to
      be float. Maybe you should rename i to something that looks less like
      an index and more like a credit.
      [color=blue]
      > credits += credlist[i][/color]

      Here, you're trying to indexa list with a float. No can do...
      [...][color=blue]
      >TypeError: list indices must be integers[/color]

      ....ss it's telling you here[color=blue]
      >
      >
      >If anyone can point me in the right direction, I would greatly appreciate
      >it.[/color]

      I think what you want is

      for cr in credlist:
      credits += cr

      Which could also be implemented as

      credits = reduce(lambda x,y: x+y, credlist)

      HTH,
      -=Dave

      --
      Change is inevitable, progress is not.

      Comment

      • andy

        #4
        Re: problem adding list values

        David M. Synck wrote:
        [color=blue]
        >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
        >
        >And the syntax error I get is this -
        >
        >Traceback (most recent call last):
        > File "./BankReconciler_ Rev1.py", line 129, in ?
        > main()
        > File "./BankReconciler_ Rev1.py", line 116, in main
        > getCredits()
        > File "./BankReconciler_ Rev1.py", line 60, in getCredits
        > credits += credlist[i]
        >TypeError: list indices must be integers
        >
        >
        >If anyone can point me in the right direction, I would greatly appreciate
        >it.
        >
        >Thanks in advance
        >
        >[/color]
        Your problem is here:

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

        In the for loop, i is successively bound to each element in credlist
        (which are floats) and you then try to index credlist with each element
        in turn: you can't index lists with floats, so you get an error.

        Try inserting a print command just before the credits expression, and
        you'll see what I mean:

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


        What you probably mean is:

        credits = 0.0
        for i in credlist:
        credits += i

        However, you should really use:

        credits = sum(credlist)

        It's far faster and more "pythonic".

        NOTE: Although it may be easy to think of Python lists as arrays,
        they're more than that. The Python for loop moves through a list,
        binding (think assigning) the loop variable (in this case "i") to each
        *element* of the list at a time on successive iterations, viz:
        [color=blue][color=green][color=darkred]
        >>> for i in ["apples","orang es","grapes","p ears","tomatoes "]:[/color][/color][/color]
        .... print i
        apples
        oranges
        grapes
        pears
        tomatoes[color=blue][color=green][color=darkred]
        >>>[/color][/color][/color]

        Hope that helps ;-)

        -andyj

        Comment

        • mrmakent@cox.net

          #5
          Re: problem adding list values

          Glad to help. Your relevant code:
          [color=blue]
          > i = 0
          > for i in credlist:
          > credits += credlist[i]
          > i = i + 1[/color]

          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.

          Comment

          • Tomasz Lisowski

            #6
            Re: problem adding list values

            Dave Hansen wrote:[color=blue]
            > I think what you want is
            >
            > for cr in credlist:
            > credits += cr
            >
            > Which could also be implemented as
            >
            > credits = reduce(lambda x,y: x+y, credlist)[/color]

            or even:

            credits = sum(credlist)

            Tomasz Lisowski

            Comment

            • gene tani

              #7
              Re: problem adding list values


              David M. Synck wrote:
              [color=blue]
              >
              > """ This function asks the user to input any credits not shown on their bank statement
              >[/color]

              (OT I know, but just so you know, you *may* get away with using floats
              for financial calculations if you're handling small numbers of floats
              of roughly same order of magnitude, but if your calculations have to
              be exact to the penny, and you have lots of numbers not of the same
              magnitudes, you probably don't want to do this.

              Comment

              Working...