import os number = [] count = 0 sum = 0 fName =input(\"Enter the file name: \")
ID: 3854923 • Letter: I
Question
import os
number = []
count = 0
sum = 0
fName =input("Enter the file name: ")
if os.path.exists(fName):
with open(fName, 'rb') as f:
try:
for line in f:
number.append(int(line))
count = count + 1
except :
print("Unable to open file: " + str(fName))
# start calculation sum,avg, max,min
i = 0
min = number[0];
max = number[0];
while i < count:
# find min
if(min > number[i]):
min = number[i]
# find max
if (max < number[i]):
max = number[i]
# calc avg
sum += number[i]
i = i + 1
avg = float(sum / count)
print('File name:' + fName)
print("Sum:" + str(sum))
print("Count:" + str(count))
print("Average:" + str(avg))
print("Maximum:" + str(max))
print("Minimum:" + str(min))
print("Range:" + str((max - min)))
Output it says
Enter the file name
If I enter djasf242 it just comes up
min = number[0];
IndexError: list index out of range
>>>
I want it to say No such file exists try again.
and it repeats the program. How do you get the program to do that.
Explanation / Answer
The answer is as follows:
As per my understanding the expectation is that till the user gives a correct filename the program should loop
asking for correct filename.
The code modification is as follows:
fName =input("Enter the file name: ")
valid = 0
while valid == 0:
if os.path.exists(fName):
valid = 1
else:
print("No such file exists try again")
fName =input("Enter the file name: ")
with open(fName, 'rb') as f:
for line in f:
number.append(int(line))
count = count + 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.