Average of numbers which are in a file

Hello! I am new to Python programming. I wrote a program that reads all the numbers and calculates the average of those numbers which are in a file. I want feedback, and criticism on how to make my program better.

infile=open(‘integers.txt’, ‘r’)

integers=infile.readlines()

count=0

sum=0

for num in integers:

sum+=int(num)

count += 1

print(“The average of the numbers is:”,sum/count)

Please wrap code in triple backticks to preserve the formatting:

```python
if True:
    print(''Hello world!')
```

open defaults to 'r', and you’re not closing the file. Using with would be better as it will automatically close the file:

with open(‘integers.txt’) as infile:
    integers = infile.readlines()

You don’t need to count the numbers, just use the len function.

2 Likes

In general it is best to use the built-in library to do these type of calculations. In this case the statistics.mean function which you can read about here:
https://docs.python.org/3/library/statistics.html