151k views
2 votes
PYTHON!HELP!Grade Average with Exceptions

the programmer needs to catch all possible exceptions within the program, give an intelligent error message to the user, and allow the user to reenter the data so the program may continue. In the Grade Average program, there are two possible exceptions that can be caused by the user; the user can type in something that is not a number, e.g. 'fred', causing a ValueError, or the user can enter a negative number without entering any numbers to average causing a ZeroDivisionError. You must modify the program to use a loop any place the user enters a number to keep requesting them to enter a number until they enter a number.

You will also add the following function to your program: calculateAverage(sum, count) where sum is the sum to be averaged and count is the count of the numbers in sum. It will return the average which is simply sum/count or it will raise a ValueError if count = 0. In the main logic of the program, you will call calculateAverage to get the average but must catch the ValueError if it is raised.

You will see that by making the program robust, you will more than double the amount of code in the assignment.

User Eladio
by
4.6k points

1 Answer

3 votes

Answer:

def calculateAverage(sum, count):

#defining variable

avg=0

try:

avg=sum/count

except ZeroDivisionError:

print("Average can'nt be calculated for 0 numbers");

return avg

#variables

count=0

sum=0

av=0

#infinite loop

while True:

try:

#getting the user input and checking the value

val=(int)(input("Enter a positive number to toal or a negative number to calculate the average: "))

if (val<0):

av=calculateAverage(sum,count)

break;

else:

sum=sum+val

count += 1

except ValueError:

print("Entered value is incorrect");

continue

#printing the average of the numbers

print("The sum is "+str(sum))

print("The Average is "+str(av))

Step-by-step explanation:

User Yoniyes
by
4.7k points