I am struggling with my Python homework. I need to write a script that reads a s
ID: 671318 • Letter: I
Question
I am struggling with my Python homework.
I need to write a script that reads a series of numbers in from a file (one number per line) and outputs the largest number, smallest number, and average. For example, given the following file:
and the ideal output will be :
-----------------------------------------------------------------------------------------
Here is my code?
File = open('numbers.txt',"r")
lines = File.readline()
for line in lines:
lines.strip()
total_number = len(File)
print('Found number: ',total_number)
This is not correct, and i don't not how to keep going, and for the first line i supposed to ask the file name like:
Please enter your file name:
and i enter file name(numbers.txt) then, my code read lines, but i don't know how.
please help!!!!
134265Explanation / Answer
filename = raw_input("Enter a file name : ")
print 'Reading '+filename
myfile = open(filename)
lines = myfile.readlines()
print 'Found ' + str(len(lines)) + ' numbers.'
number = []
for line in lines:
line = line.strip()
number.append(int(line))
print 'Largest number : '+ str(max(number))
print 'Smallest number : '+ str(min(number))
print 'Average : '+ str(sum(number)*1.0/len(number))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.