Bryan McCormack
Bryan McCormack

Reputation: 105

How do I change datatype in Program?

I am working on a program that takes a column from a csv file and averages the sales data, but I am getting an error: "unsupported operand type(s) for +: 'int' and 'str'"

I changed the column in the csv file to numbers and I still get the error.

from csv import reader
opened_file = open('Catalog.csv')
read_file = reader(opened_file)
catalog_data = list(read_file)


sales_data = []
for stuff in catalog_data:
price = stuff[11]
manufacturer = stuff[7]

if manufacturer == 'HASBRO':
    sales_data.append(price)

avg_sales = sum(sales_data) / len(sales_data)

Upvotes: -1

Views: 37

Answers (3)

Bryan McCormack
Bryan McCormack

Reputation: 105

The int function appened doesn't work:

from csv import reader
opened_file = open('Catalog.csv')
read_file = reader(opened_file)
catalog_data = list(read_file)


sales_data = []
for sales in catalog_data:
    price = int(sales[11])
    manufacturer = sales[7]

    if manufacturer == 'HASBRO':
        sales_data.append(int(price))


avg_sales = sum(sales_data) / len(sales_data)

Upvotes: 0

user2209008
user2209008

Reputation:

When you're reading in from a CSV file, all the values are strings.

price = stuff[11]

At this point, price is a string. So when you go:

sales_data.append(price)`

sales_data is being populated with a list of strings.

When you eventually call sum(sales_data), the sum function fails because it's assuming that sales_data is populated with numeric values.

To remedy this, simply cast the price data to an appropriate value, like so:

price = float(stuff[11])

Note that if floating point values can lose precision, so it's generally not recommended to use float values to store currency values. If precision is important, consider using the decimal module.

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

use casting like below for price

price = float(stuff[11])

Upvotes: 2

Related Questions