0

I feel a bit blonde right now, but for some reason I can't figure out how to solve this.

Need to correct these two issues.

  1. using // integer division messes up the average.
  2. Also, I need to use the format function to get 2 decimal places

    def viewscores(scores):

    sum_scores = sum(scores)
    average = float(sum_scores // len(scores))
    ### here is where I am having the results displayed
    
    print ("The scores are these: " + str(scores))
    print ("The Average score now is: " + str(average))
    

    def main():

    scores = []
    
    scores_file = open('scores.txt', 'r')
    line_list = list(scores_file.readlines())
    
    scores_file.close()
    i = 0
    while i < len(line_list):
        scores.append(int(line_list[i].strip()))
        i += 1
    viewscores(scores)
    

    main()

sarah
  • 3
  • 3
  • 1
    If `sum_score` is an integer, then make it a float before you divide it by an integer. Mess around with dividing with integers, and you will see why. –  Jun 24 '15 at 03:06
  • Don't use _floored_ division. [Format string syntax](https://docs.python.org/3/library/string.html#format-string-syntax). – wwii Jun 24 '15 at 03:13

3 Answers3

2

This is one of those things where Python2 and Python3 behave differently.

using // integer division messes up the average.

Python 3:

average = sum_scores / len(scores)

Python 2:

average = float(sum_scores) / len(scores)

In either case, you don't want to use //.

Also, I need to use the format function to get 2 decimal places

Python 3:

print ('The average score now is {:.2f}'.format(average))

Python 2:

print ('The average score now is %.2f' % average)

Even within each dialect there's multiple solutions.

QuestionC
  • 10,006
  • 4
  • 26
  • 44
  • 3
    Don't forget that you can make Python 2's `/` operator behave like Python 3's with `from __future__ import division`. – dan04 Jun 24 '15 at 03:58
0

The most simple option would be to use format(scores, '.2f')

sum_scores = float(sum(scores))
average = (sum_scores / float(len(scores)))


print ("The scores are these: %s" %format(scores, '.2f'))
print ("The Average score now is: %s"  %format(average, '.2f')
user3636636
  • 2,409
  • 2
  • 16
  • 31
0

i am new to Python as well.

For "//", i gave a trial on ipython, to me they do not make much difference whether you use // or /

For two decisoinal place problem, i learnt something from the following

For function, you may wish to consult Google

  • i am not good at creating function, but function always should have "return", because everything in python is object
Community
  • 1
  • 1
user381509
  • 65
  • 7