0

The code below is working completely fine, however I want to add the mean average of the inputted numbers (stored in a .txt file). Im thinking i will have to put the inputted values on different lines but im not sure how to do that either. Is there a simple way to do this?

myFile = open("C38test.txt","wt")
myFile.write(input("Enter numbers to put in a list, leave a space between each number. \n"))
myFile.close()

myFile = open("C38test.txt","rt")
contents = myFile.read()
user_list = contents.split()

for i in range(len(user_list)):
             user_list[i] = int(user_list[i])
print("Sum = ",sum(user_list))
    
Josh
  • 3
  • 5

1 Answers1

0

Note: This question is very similar to this question.

The average, or mean, of a set of values is the sum of all the values divided by the number of values.

There are two main ways I have found:

Method 1: use the sum and len functions average = sum(user_list)/len(user_list), and then you can do whatever you want with the variable average of type int

Method 2: use the statistics module to do it for you

On Python 3.8+ (works with floats)

import statistics
average = statistics.fmean(user_list)

On Python 3.4+

import statistics
average = statistics.mean(user_list)

Not sure about the add-on about putting it in a file, but you can do

with open("filename.txt", "w") as fout:
    fout.write(str(average))
kenntnisse
  • 429
  • 2
  • 12
  • I'm kind of new here, so I thought this question sounded like [this one](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list), but it wanted to know how to put it into a file... Does that meet the criteria for a duplicate question? – kenntnisse Mar 17 '22 at 17:42
  • Yes that would be the way to do it if the array was given. However this array is inputted and python will read each individual characters rather than the amount of actual numbers there are and so will divide by the wrong thing, which is what is confusing me. If I inputted “10 20 30” into the program, rather than counting 3 numbers it will count 8 characters. This has really confused me because it seems like something really simple yet just isn’t happening. Thanks for the info though, will certainly have a look at that statistics module. – Josh Mar 17 '22 at 22:51
  • @Josh wdym? In your original code, it already has a list of all the values in `user_list`. And the `len` function gets the number of items in the list. The `split` function separates by whitespace, so "10 20 30" would be split into ["10", "20", "30"], which you've converted to `int`s. I'm not sure what you are saying... – kenntnisse Mar 18 '22 at 15:16
  • Good point haha, I didn’t realise it was separated by whitespace, good to know! i will attempt this tomorrow and hopefully it should work. Apologies for the comment, thanks! – Josh Mar 18 '22 at 22:16