Python Forum

Full Version: Excel file reading problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello to all,

the following program should indicate the average number of emissions by reading an excel file.
Excel file has to columns, one for company, the other for emissions.

Do you know why total_emissions=0?
I think the program is not able to read the excel file correctly but I don't know what else to do.

The goal would be to have 0.5*6008+0.5*4051=5029 and so D- grade.
Thanks

Code is:
from openpyxl import load_workbook
wb = load_workbook('')
sheet = wb.active
companies = input('Enter the companies in the portfolio, separated by commas: ').split(',')
weights = input('Enter the weights of each company, separated by commas: ')
total_emissions = 0
for i in range(len(companies)):
  # Get the company name and weight
  company = companies[i]
  weight = weights[i]
  for row in sheet.rows:
    if row[0].value == company:
      total_emissions += row[1].value * weight
print(total_emissions)
if total_emissions <= 250:
  grade = 'A+'
elif total_emissions <= 500:
  grade = 'A'
elif total_emissions <= 750:
  grade = 'A-'
elif total_emissions <= 1000:
  grade = 'B+'
elif total_emissions <= 1250:
  grade = 'B'
elif total_emissions <= 1500:
  grade = 'B-'
elif total_emissions <= 2000:
  grade = 'C+'
elif total_emissions <= 2500:
  grade = 'C'
elif total_emissions <= 3000:
  grade = 'C-'
elif total_emissions <= 4000:
  grade = 'D+'
elif total_emissions <= 5000:
  grade = 'D'
elif total_emissions <= 6000:
  grade = 'D-'
else:
  grade = 'F'

print(f'The grade for the portfolio is: {grade}')
Enter the companies in the portfolio, separated by commas: LAFARGE HOLCIM, TECHNIPFMC PLC
Enter the weights of each company, separated by commas: 0.5,0.5
0
The grade for the portfolio is: A+
Your posted code cannot work. weight is not a number. I pulled out the code where you enter the companies and weights.
companies = input('Enter the companies in the portfolio, separated by commas: ').split(',')
weights = input('Enter the weights of each company, separated by commas: ')
for i in range(len(companies)):
    company = companies[i]
    weight = weights[i]
    print(company, weight)
Output:
A 1 B , C
Two things to note.
1. weight is a string, not a number. The weights are "1", ",", " ".
2. company strings include leading whitespace.

Consider using pandas instead of openpyxl. pandas will do a much better job reading an excel spreadsheet than any code you or I can hope to write.