[Tutor] TypeError: 'float' object is not iterable
Peter Otten
__peter__ at web.de
Thu Jul 23 03:57:28 EDT 2020
hongerlapjes wrote:
> I'm learning python and need help. How can I sum up "bedrag"?
> I've replaced the "." with a "," and changed the string into a float,
> but I can't iter. I'm lost. What do I need to do?
The iteration is done by your for loop. You need another variable that you
initialize before it:
totaalbedrag = 0.0
for row in csv_reader:
bedrag = float(row['Bedrag (EUR)'].replace(",", "."))
totaalbedrag = totaalbedrag + bedrag
print(totaalbedrag)
A more concise way to spell that is
totallbedrag = sum(
float(row['Bedrag (EUR)'].replace(",", "."))
for row in csv_reader
)
print(totaalbedrag)
Here the loop is moved into the "generator expression" that is used as the
argument for the sum function.
If you are doing that or simalar operations a lot you should look at pandas
(built on top of numpy) which gives you highlevel operations to do the same:
>>> import pandas as pd
>>> df = pd.read_csv("oefen.csv")
>>> df
Bedrag
0 1.23
1 2.34
[2 rows x 1 columns]
>>> df["Bedrag"].sum()
3.5699999999999998
More information about the Tutor
mailing list