I am taking an introductory course in Python and am currently discovering how to handle files using Python. I have a CSV file with a few student names, their majors and GPAs
I am trying to handle the file on python to calculate and print the average of the GPAs
This is a snippet of the csv file:
Ahmed Yousry,2.99,Accounting Amina Hamdy,2.45,Marketing Hala Hossam,3.85,BIS Dina Gamal,3.96,BIS Amr Nabil,3.6,Finance
and this is the code I was trying to write:
import csv f1 = open("myText.csv") rowlist = csv.reader(f1) sum = 0 for row in rowlist: sum += row avg = sum / 5 f1.close() print("Average GPA is", avg)
However, I keep getting an error that the sum cannot be calculated since it is reading the GPA values as strings not integer values and I have no idea how to convert them
here is what the error message says:
Traceback (most recent call last): File "C:\Users\user\PycharmProjects\practicefiles\program12.py", line 6, in <module> sum += row TypeError: unsupported operand type(s) for +=: 'int' and 'str'
could someone tell me where I’m going wrong? I’ve tried casting the value as an int and it still won’t work and I don’t know what else could be done
Thank you in advance to those who help out
float() function to convert string to float type.
import csv f1 = open("myText.csv") rowlist = csv.reader(f1) sum = 0 for row in rowlist: sum += float(row) avg = sum / 5 f1.close() print("Average GPA is", avg)