473,395 Members | 1,466 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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
Dec 22 '05 #1
6 2295

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

Dec 22 '05 #2
On Thu, 22 Dec 2005 19:43:15 GMT in comp.lang.python, "David M. Synck"
<dm*****@verizon.net> wrote:

[...]
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"))
Here you're building credlist as a list of floats.

i = 0
This is wasted effort
for i in credlist:
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.
credits += credlist[i]
Here, you're trying to indexa list with a float. No can do...
[...]TypeError: list indices must be integers
....ss it's telling you here

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


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.
Dec 22 '05 #3
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

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

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:
for i in ["apples","oranges","grapes","pears","tomatoes"]: .... print i
apples
oranges
grapes
pears
tomatoes


Hope that helps ;-)

-andyj
Dec 22 '05 #4
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.

Dec 22 '05 #5
Dave Hansen wrote:
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)


or even:

credits = sum(credlist)

Tomasz Lisowski
Dec 23 '05 #6

David M. Synck wrote:

""" This function asks the user to input any credits not shown on their bank statement


(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.

Dec 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Phillip | last post by:
Hi. I hate the way one has to jump through countless hoops to put data in a db and get it out again. The straightforward MySQLdb Interface requireing this SQL stuff being a point in case (against...
3
by: VIJAY KUMAR | last post by:
Hi pals, I am using 2 web forms (pages). In first page, i have Datagrid control and on second page i have a hyper link control to the first page and Add value to the data grid/Database. ...
0
by: Jongmin | last post by:
I met a problem when implementing IBindingList interface. I made CustomerList class, copied from MSDN, to implement CollectionBase and IBindingList. My problem took place after setting...
2
by: Andrés Giraldo | last post by:
Hi! I'm adding rows dinamically to a System.Web.UI.WebControls.Table, on depends on a dropdown listbox's selected item, on a Cell of the table I'm adding a TextBox, it's Text property it's a...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
2
by: drdave | last post by:
Hi All, I'm filling an arraylist with other arraylists within a loop and within the first iteration and addition all is fine.. however when I clear my value holding temporary array I lose the...
2
by: Mike Collins | last post by:
I cannot get the correct drop down list value from a drop down I have on my web form. I get the initial value that was loaded in the list. It was asked by someone else what the autopostback was...
1
by: napolpie | last post by:
----Messaggio originale---- Da: napolpie@tin.it Data: 3-mag-2007 10.02 A: <python-list@python.org> Ogg: problem with meteo datas Hello, I'm Peter and I'm new in python codying and I'm using...
0
by: mgilligan | last post by:
Hi I am having a problem and can not for the life of me figure out what is wrong. I have a program that iterates through every file in a directory using FindFirstFile and FindNextFile and add them...
4
by: Clive Lumb | last post by:
Hi, I'm having a problem while adding objects to a collection. (VB.net 2005) I am reading data in from a file to a temporary variable (eg MyClass) and then adding it to a collection. When I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.