Search code examples
pythonpython-3.xtypeerror

How do I properly manage the TypeError in my program?


I can't figure out how to handle any exceptions for non-int or float inputs on the program below. Could you guys please point me in the right direction?

def GradeAverager(): #Creating the function of the grade averager
    #User initiation input
    response = input("\n\nWould you like to average your grades? Press Y for "
                     "Yes or N to exit: ")

    #Defined controlled repsonse variables
    y="Y"
    n="N"

    if response in ["y","Y"]: #If statement based on response (allows for
                              #different variatios of the inputs)

        # User input the # of grades to average
        numOfGrades = float(input("\n\nEnter number of grades to be averaged: "))

        if type(numOfGrades) is not float:
            #Handles non-int exception (NOT WORKING)
            raise TypeError("Only Numbers please!")

        #Defining the variables for the while statement
        x=0
        grades = 0
        rounded_average = 0
        while x < numOfGrades: # While loop to keep asking the user for grades
                               # based on "numOfGrades"
            grades += float(input("\n Enter Grade: ")) # User input is taken
                                                       # and added to grades

            if not type(grades) is not float:
                #Handles non-int exception (NOT WORKING)
                raise TypeError("Only Numbers please!")

            x += 1 # keeps the loop repeating until it is no longer true
        average = grades/numOfGrades # Takes the total of grades and divides it
                                     # by numOfGrades to calculate average
        rounded_average = round(average, 1) #Rounds the total to two one decimal
        print("\n\nYour Grade Average is: " + str(rounded_average))

        #If statements based on result scores
        if average > 70:
            print("\n You are passing but should study harder :|\n\n")
        elif average > 80:
            print("\n Good Job! you're getting there! :)\n\n")
        elif average > 90:
            print("\n Awesome Job! You are Acing this! XD\n\n")
        else:
            print("\n You need to go back and study! :(\n\n")

    elif response in ["n","N"]: #If user answers "no", ends the program
        print("\n\nGood Luck!\n\n")
    else:
        print("\n\nIncorrect Entry\n\n")
        GradeAverager()


print("\n\n*****Welcome to the Grade Averager******") #Prints the title
GradeAverager() #Calls the function

Solution

  • You just have an extra "not" in the line:

    if not type(grades) is not float:
    

    Change it to:

    if not (type(grades) is float):
    

    But in general it's better to do it like this:

    if isinstance(grades, float):
    

    but if you dig deeper, you'll realize that grades will always be of type float, only if the value from the input is correct. You need to check this. Review this and decide how best to check if the input value is a valid representation of a number.

    UPD:

    And as rightly noted in the comments, almost the same with the numOfGrades variable