0

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')
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45
Hao
  • 23
  • 7
  • possible dup : https://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10 – Jack Dorset Apr 05 '19 at 13:38
  • `user,tribe,id, *scores= row` should be `user,tribe,id, *scores= row.values()`. If you'd put a simple `print(row)` on every iteration, you would see that `row`s are dicts. I'm flagging the question as a typo. – Georgy Apr 05 '19 at 14:48

3 Answers3

0

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
BoarGules
  • 16,440
  • 2
  • 27
  • 44
0

replace

*scores= row

with

scores = row['Score1']+row['Score2']+row['Score3']+row['Score4']
user69659
  • 199
  • 5
0

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))
MUNGAI NJOROGE
  • 1,144
  • 1
  • 12
  • 25