-1

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) 

3 Answers 3

2

use casting like below for price

price = float(stuff[11]) 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thats the best answer IMO.
0

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) 

1 Comment

what about the int() function doesn't work? does it give an error message?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.