Need to find the average of scores of the user when user inputs the gamer id

The csv file:

name tribe id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78

Gyatso Omaticay O111C 54 78 65 54

i tried adding in some stuff I found on SO, but got the error: invalid literal for int() with base 10: 'Score1'. Will appreciate anyone that can point me in the right direction, just began learning python.

import  csv
filePath="data.csv"


with open(filePath) as csvfile:
    avatar_id=  input ("Enter Avatar ID:")    
    reader = csv.DictReader(csvfile)  
    for row in reader:
        if avatar_id in row['id']:
        #just print some stuff
            user,tribe,id, *scores= row 
            average= sum([int(score) for score in scores])/4
              print("{0:>6}{1:>8}{2:>7}{3:>7}{4:^14}".format(row['Air'],row['Water'],row['Earth'],row['Fire'], average))
            print("==============================") 
        else:
            x=5
if x>4:
    print('No avatar found')

3 Answers

0
BoarGules On Best Solutions

Your error tells you exactly what the problem is. Your code is trying to convert the header label Score1 to an integer in this line:

average= sum([int(score) for score in scores])/4

and failing. To avoid including the header labels in the computation, test reader.line_num to skip the first line of the file.

Or, to be safe, just ignore any non_numeric data:

if all(score.isdigit() for score in scores):
    average= sum([int(score) for score in scores])/4
0
user69659 On

replace

*scores= row

with

scores = row['Score1']+row['Score2']+row['Score3']+row['Score4']
0
MUNGAI NJOROGE On

You need to add an extra check for not existent keys and remove empty rows in your CSV file. You also need to add delimiter to your csv.DictReader as it defaults to comma separator. See example bellow:

import  csv
import io
filePath="""name tribe id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78
Gyatso Omaticay O111C 54 78 65 54
"""

avatar_id=  input ("Enter Avatar ID:")    
reader = csv.DictReader(io.StringIO(filePath),delimiter=' ')  
for row in reader:
    print(row)
    if avatar_id in row.get('id',''):
        user,tribe,id, *scores= row.values()
        average= sum([int(score) for score in scores])/4
        print("==============================") 
        break
    else:
        x=None
if x is None:
    print('No avatar found')
else:
    print("{} score is {}".format(avatar_id,x))