InfoTc 1040 Introduction to Problem Solving and Programming Number Stats 1 (Pyth
ID: 3676279 • Letter: I
Question
InfoTc 1040 Introduction to Problem Solving and Programming Number Stats 1 (Python 3.5)
In this programming assignment you are to create a program called numstat.py that reads a series of integer numbers from a file and determines and displays the following:
• The name of the file.
• The sum of the numbers.
• The count of how many numbers are in the file.
• The average of the numbers. The average is the sum of the numbers divided by how many there are.
• The maximum value.
• The minimum value.
• The range of the values.
The range is the maximum value minus the minimum value. The program is to prompt the user for the name of the file that contains the numbers. If an exception occurs trying to open or read the file an error message is to be displayed. The program is not to crash if the file is not found or there is an error reading the file. Use try-except! The output from the program is to display the information described above using the following strings preceding the values. There is to be a space between the colon and the value. File name: Sum: Count: Average: Maximum: Minimum: Range: At the end of one attempt at reading, or a successful read, of a file the user it to be asked if they would like to evaluate another file of numbers. Use the prompt: Would you like to evaluate another file? (y/n) If the user answers y, then the program is to accept input for another file name. If the user answers with anything other than y, the program is to exit.
Explanation / Answer
from sys import maxint
fileName = raw_input("Enter file name:")
try:
handle = open(fileName)
except IOError:
print "File not found!"
sum = 0
minInt = maxint
maxInt = -maxint-1
count = 0
for line in handle:
try:
integer = int(line)
count+=1
sum += integer
if integer > maxInt:
maxInt = integer
if integer < minInt:
minInt = integer
except ValueError:
print "Error reading file!"
print "File name: ", fileName
print "Sum: ", sum
print "Count: ", count
print "Average: ", (sum/count)
print "Maximum: ", maxInt
print "Minimum: ", minInt
print "Range: ", (maxInt-minInt)