File Loops

In [7]:
from random import sample
def make_nums(nums):
    outfile = open("data.txt", 'w')
    for n in sample(range(2000), k=nums):
        outfile.write(str(n) + "\n")
        outfile.write("\n")
    outfile.close()
In [9]:
def average5():
    filename = input("Filename of numbers: ")
    infile = open(filename, 'r')
    _sum = 0.0
    count = 0
    
    for line in infile:
        _sum = _sum + float(line)
        count = count + 1
        
    print("\nThe average of the numbers is", _sum/count)
    infile.close()
In [8]:
make_nums(10)
In [10]:
average5()
Filename of numbers: data.txt
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-a02a82fa0abe> in <module>()
----> 1 average5()

<ipython-input-9-e8e13fbd2176> in average5()
      6 
      7     for line in infile:
----> 8         _sum = _sum + float(line)
      9         count = count + 1
     10 

ValueError: could not convert string to float: 
In [18]:
def average6():
    filename = input("Filename of numbers: ")
    infile = open(filename, 'r')
    _sum = 0.0
    count = 0
    
    line = infile.readline()
    while line != "":
        if line != "\n":
            _sum = _sum + eval(line)
            count = count + 1
        line = infile.readline()
        
    print("\nThe average of the numbers is", _sum/count)
    infile.close()
In [19]:
average6()
Filename of numbers: data.txt

The average of the numbers is 970.2
In [ ]:
 
In [ ]: