Trenton Hallmark Trenton Hallmark - 2 months ago 9
Python Question

Print Highest, Average, Lowest score of a file

i'm trying to print the highest, average, and lowest score of a file in python. But I keep getting error ValueError: invalid literal for int() with base 10.

My results.txt file looks like this,

Johnny-8.65
Juan-9.12
Joseph-8.45
Stacey-7.81
Aideen-8.05
Zack-7.21
Aaron-8.31


And my code looks like this


func1={} with open('results.txt','r') as f:
for line in f:
name,value=line.split('-')
value=float(value)
if name in func1.keys():
func1[name].append(value)
else:
func1[name]=[value]


compute average: for name in func1:



average=sum(func1[name])/len(func1[name])
print("{} : {}".format(name,average))


Answer

Values that you provided in file are not int type. For your approach you can use float():

value = float(value)

If you need to extract integer:

s = "123"
num = int(s)

num = 123

If you need to extract float number:

s = "123.12"
num = float(s)

num = 123.12

You can refer to documentation: Datatypes #1Datatypes #2

Also there is nice post about converting number datatypes in python: Parse String to Float or Int

How to get maximum key / value from dictionary refer to: get max valueget max key

Also, read this article. It will help you to answer clear questions. How do I ask and answer homework questions?